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.
two pointers and move from the end because it is a non-decreasing array.
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.
"""
# 0. nums1 앞부분 복사한 array 생성
arr = copy.deepcopy(nums1[0:m])
# 1. 순서 알려줄 check 생성
check_1 = 0
check_2 = 0
i = 0
# 2. check로 크기 비교하여 넣기
while check_1 < m and check_2 < n:
if arr[check_1] >= nums2[check_2]:
nums1[i] = nums2[check_2]
check_2 = check_2 + 1
i = i + 1
else:
nums1[i] = arr[check_1]
check_1 = check_1 + 1
i = i + 1
# 3. 남은 숫자 넣기
if check_1 < m:
for j in range(check_1, m):
nums1[i] = arr[j]
i = i + 1
if check_2 < n:
for j in range(check_2, n):
nums1[i] = nums2[j]
i = i + 1
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.
"""
del nums1[m:]
nums1 += nums2
nums1.sort()


첫번째 방식이 시간은 덜 사용하지만 메모리를 조금 더 쓰고, 두번째 방식이 런타임이 더 오래 걸리는 것을 알 수 있다.
