Merge Sorted Array
Problem statement
You are given two integer arrays, nums1 and nums2, and two integers, m and n.
The first m values of nums1 are its real values. Its last n slots hold 0 and are empty space. nums2 holds exactly n values. The real values of nums1 and all values of nums2 are sorted in non-decreasing order.
Merge nums2 into nums1 so that nums1 holds all m + n values in non-decreasing order, then return nums1.
Follow-up
Now suppose neither array has empty space: one array holds m values and the other holds n values. Without using another array, how would you rearrange the values so that the first array holds the m smallest values and the second holds the rest, both sorted? Your function only solves the version above. The editorial covers this follow-up.
Function
merge(nums1: int[], m: int, nums2: int[], n: int) → int[]Examples
Example 1
nums1 = [1,2,3,0,0,0]m = 3nums2 = [2,5,6]n = 3return = [1,2,2,3,5,6]The real values are [1,2,3] in nums1 and [2,5,6] in nums2. Merged in order, they give [1,2,2,3,5,6], which fills all six slots of nums1.
Example 2
nums1 = [1]m = 1nums2 = []n = 0return = [1]nums2 is empty, so nums1 stays [1].
Example 3
nums1 = [0]m = 0nums2 = [1]n = 1return = [1]m is 0, so nums1 has no real values. Its only slot is empty space, and the result is [1].
Constraints
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-10^9 <= nums1[i], nums2[j] <= 10^9- The first
mvalues ofnums1and all values ofnums2are sorted in non-decreasing order. - The last
nvalues ofnums1are0.