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.
문제링크: https://leetcode.com/problems/merge-sorted-array/
여러가지 방법이 있을수 있겠지만, 단순히 two pointer 를 사용하여 두개 의 포인터가 각자 배열의 끝을 가르키고,각각의 포인터의 인덱스를 하나씩 줄여가면서 nums1 배열에 num2 배열의 값을대입하면 될것이라고 생각했다.
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
ptr1 = len(nums1) -1
ptr2 = len(nums2) -1
while(ptr2 >-1): # O(N)
nums1[ptr1] = nums2[ptr2]
ptr2 -=1
ptr1 -=1
nums1.sort() #O((M+N)log(M+N))
ptr2 가 0이 될때까지 배열을 돌아야 하므로 O(N)이 걸리는것은 자명해보인다. 하지만 마지막에 배열을 정렬하는 부분이 추가되어서 O((N+M)log(N+M)) 만큼의 시간복잡도가 추가로 더 필요하다. 이 부분을 개선해 보고자 다른사람의 풀이를 찾아보았다.
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
ptr1 = m -1
ptr2 = n -1
ptr3 = m + n -1
while ptr2 >= 0: #O(N)
if ptr1 >= 0 and nums1[ptr1] > nums2[ptr2]:
nums1[ptr3] = nums1[ptr1]
ptr1 -= 1
else:
nums1[ptr3] = nums2[ptr2]
ptr2 -= 1
ptr3 -= 1
다른사람의 풀이를 참고하여 시간복잡도를 줄여보았다.
두 배열에서 각 원소를 비교하고, 큰 원소를 nums1 배열의 끝부분 부터 채워준다. 이렇게 함으로써 배열을 다시 정렬해주는 부분을 제거 할 수 있으며, O(N)만큼의 시간복잡도로 만들어 줄수있다.