You are given two integer arrays, nums1 and nums2, both sorted in non-decreasing order. Your task is to merge these two arrays into a single new sorted array.
Solution
The most straightforward approach involves using two pointers.
- Initialize two pointers,
p1fornums1andp2fornums2, both starting at index0. - Create an empty
resultarray to store the merged elements. - While both
p1is withinnums1bounds andp2is withinnums2bounds:- Compare
nums1[p1]andnums2[p2]. - Append the smaller element to
resultand increment its corresponding pointer.
- Compare
- After the loop, one of the arrays might still have remaining elements. Append all remaining elements from
nums1(if any) andnums2(if any) toresult. - Return the
resultarray.
def merge_sorted_arrays(nums1: list[int], nums2: list[int]) -> list[int]:
p1 = 0
p2 = 0
result = []
while p1 < len(nums1) and p2 < len(nums2):
if nums1[p1] < nums2[p2]:
result.append(nums1[p1])
p1 += 1
else:
result.append(nums2[p2])
p2 += 1
# Append remaining elements from nums1, if any
while p1 < len(nums1):
result.append(nums1[p1])
p1 += 1
# Append remaining elements from nums2, if any
while p2 < len(nums2):
result.append(nums2[p2])
p2 += 1
return result
