Merge Sorted Array

Given two sorted integer arrays, merge the second array into the first one in non-decreasing order. The first array has enough extra space at the end to hold all elements. The task tests whether sorting first makes the merge step straightforward and linear.

Input Format

nums1 = first sorted array with extra trailing space, m = valid elements in nums1, nums2 = second sorted array, n = its length

Output Format

nums1 modified in non-decreasing order

Constraints

  • 1 <= m + n <= 10^5; -10^9 <= nums1[i], nums2[i] <= 10^9

Examples

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:

Merge the two sorted arrays in place.

Example 2:

Input:

nums1 = [1]
m = 1
nums2 = []
n = 0

Output:

[1]

Explanation:

No elements are added from the second array.

Loading...
Merge Sorted Array