Merge Sorted Array
easy
arrays
two-pointers
sorting
Problem
You are given two sorted integer arrays: nums1 and nums2. The array nums1 has length m + n, where the first m values are meaningful sorted elements and the last n values are placeholder zeroes. The array nums2 has length n and is also sorted. Return the fully merged sorted array of length m + n. The judge checks the returned array, so you may mutate nums1 in place and return it, or build a new array and return that instead.
Input / output
- Input:
nums1: int[],m: int,nums2: int[],n: int - Output:
int[], the merged sorted array of lengthm + n
Examples
nums1 = [1,2,3,0,0,0],m = 3,nums2 = [2,5,6],n = 3returns[1,2,2,3,5,6].nums1 = [1],m = 1,nums2 = [],n = 0returns[1].nums1 = [0],m = 0,nums2 = [1],n = 1returns[1].
Constraints
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-10^9 <= nums1[i], nums2[i] <= 10^9for meaningful values- The first
mvalues innums1are sorted in non-decreasing order. nums2is sorted in non-decreasing order.
Follow-up
Can you solve it in O(m + n) time using only O(1) extra space by writing the merged result from the end of nums1 backward?
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]
Example 2
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Example 3 (nums1 starts empty)
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]