Skip to main content

Merge Sorted Array

EasyPremium

You're given two arrays sorted in non-decreasing order, nums1 and nums2, and two integers m and n. The first m elements of nums1 are real values. Its last n slots hold 0 as placeholders, so nums1 has length m + n. nums2 has exactly n values.

Merge nums2 into nums1 so that nums1 ends up holding all m + n values in sorted order. Modify nums1 in place and don't return anything.

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]

The three zeros at the end of nums1 are space for the values from nums2.

Example 2

Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1]

With m = 0, the 0 in nums1 is a placeholder, not a value.

Constraints

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • -10^9 <= nums1[i], nums2[j] <= 10^9