non-decreasing order

비내림차순 정렬. gpt가 설명해주기론 [1, 2, 2, 4] 를 비내림차순 정렬하면 2와 2의 순서가 고정되지만, 오름차순으로 정렬하면 순서가 바뀔 수도 있다고 한다.

 

The final sorted array should not be returned by the function,

num1 = nums1 + nums2

으로 했더니 입력값 그대로 [1,2,3,0,0,0]을 반환했다. 왜 안 됨? 하다가 function 쓰지 말라고 해서 그런가 했다

 

 

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        i = m - 1
        j = n - 1        
        for p in reversed(range(len(nums1))):
            if(j == -1 and i == -1):
                break
            elif(i == -1):
                nums1[p] = nums2[j]
                j -= 1
            elif(j == -1):
                nums1[p] = nums1[i]
                i -= 1
            elif(nums1[i] <= nums2[j]):
                nums1[p] = nums2[j]
                j = j - 1
            else:
                nums1[p] = nums1[i]
                nums1[i] = 0
                i = i - 1
class Solution:
    def merge_gpt(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        # nums1 배열의 끝 인덱스
        end = m + n - 1
        
        # nums1 배열과 nums2 배열을 뒤에서부터 비교하여 큰 수를 nums1 배열의 끝에서부터 채워넣음
        while m > 0 and n > 0:
            if nums1[m-1] > nums2[n-1]:
                nums1[end] = nums1[m-1]
                m -= 1
            else:
                nums1[end] = nums2[n-1]
                n -= 1
            end -= 1
        
        # nums1 배열이 비어있을 경우, nums2 배열의 나머지 요소들을 nums1 배열에 복사함
        if n > 0:
            nums1[:n] = nums2[:n]
        print(nums1)

 

보이기에는 gpt가 만든 코드가 깔끔한데 성능은 내가 만든 것이 조금 더 낫다. 왜인지는 모르겠다. 코딩은 어렵다.

+ Recent posts