Merge Sorted Array
You get two arrays sorted in ascending order. The first one ends with empty cells, exactly as many as there are numbers in the second. Merge the second array into the first, right inside it, so that the first stays sorted. Our example: [2, 5, 8, _, _, _] and [1, 6, 9] give [1, 2, 5, 6, 8, 9].
- input
nums1:mintegers in non-decreasing order, thennzeros, room fornums2;nums2:nintegers in non-decreasing order.- returns
- Nothing: change
nums1in place so that it holds allm + nnumbers in non-decreasing order. - constraints
- nums1.length = m + n, nums2.length = n
- 0 ≤ m, n ≤ 200, 1 ≤ m + n ≤ 200
- −10⁹ ≤ nums1[i], nums2[j] ≤ 10⁹
- the first m of nums1 and all of nums2 are in non-decreasing order; the last n of nums1 are 0
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
function merge(nums1, m, nums2, n) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more two pointers problems
- 125Valid PalindromeEasysolve
- 26Remove Duplicates from Sorted ArrayEasysolve
- 283Move ZeroesEasysolve
- 27Remove ElementEasysolve
- 392Is SubsequenceEasysolve
- 167Two Sum II - Input Array Is SortedMediumsolve
- 153SumMediumsolve
- 11Container With Most WaterMediumsolve
- 80Remove Duplicates from Sorted Array IIMediumsolve
- 189Rotate ArrayMediumsolve
- 151Reverse Words in a StringMediumsolve
- 5Longest Palindromic SubstringMediumsolve
- 42Trapping Rain WaterHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.