컴퓨터공학/LeetCode Solutions

[LeetCode] 88. Merge Sorted Array

saurus2 2022. 12. 30. 13:56

88. Merge Sorted Array

Easy

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

 

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Example 3:

Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

 

Constraints:

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -109 <= nums1[i], nums2[j] <= 109

 

Follow up: Can you come up with an algorithm that runs in O(m + n) time?


문제 풀이

  • 이미 오름차순으로 정렬되어있는 두 배열을 합쳐야한다.
  • 합친 배열의 결과도 오름차순으로 정렬이 되어 있어야한다.
  • 첫번째 배열을 답으로 만들어야한다.
  • 제한 사항을 보면 두 배열의 길이가 최대 200개 이기 때문에 브루트 포스로 풀어도된다. 
  • 투포인터로 문제를 푸는 방법은 다음과 같다. 
  • 투포인터가 의미하는 것은 데이터를 가르키는 포인터 두개를 사용하여 문제를 푸는 것이다.
  • 문제에서 nums1 배열의 크기는 nums1 + nums2 배열의 길이와 같으며 숫자가 채워질 빈공간은 0으로 표기되어있다.
  • nums1 배열에 중복되는 동작없이 숫자를 넣기 위해서는 맨 뒤의 인덱스부터 시작해야한다. 
  • 그 이유는 이미 숫자가 정렬되어 있기 때문에 비어있는 공간부터 채워나갈 때 가장 효율적으로 숫자들을 합칠 수 있다.
  • 각각의 배열에서 마지막 숫자는 각각의 배열들의 가장 큰 숫자이다. 
  • 그 숫자들을 가르키는 포인터 두개를 생성하여 비교하며 빈공간이 있을 수 있는 맨 마지막 부터 쌓아나간다.
  • 저장할 자리는 for 문으로 뒤에서 부터 시작하고 포인터 두개는 for 문 한번에 한개씩 움직인다.
  • 즉 O(N) 시간으로써 for 문은 한번 nums1 배열을 뒤에서부터 탐색하고, 포인터 두개가 각각 숫자들을 선택하여 비교한다.

소스 코드

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.
        """
        pointer1, pointer2 = m - 1, n - 1
        for i in range(len(nums1)-1, -1, -1):
            if pointer1 >= 0 and pointer2 >= 0:
                if nums1[pointer1] >= nums2[pointer2]:
                    nums1[i] = nums1[pointer1]
                    pointer1 -= 1
                else:
                    nums1[i] = nums2[pointer2]
                    pointer2 -= 1
            elif pointer1 >= 0:
                nums1[i] = nums1[pointer1]
                pointer1 -= 1
            elif pointer2 >= 0:
                nums1[i] = nums2[pointer2]
                pointer2 -= 1