88. Merge Sorted Array
https://leetcode.com/problems/merge-sorted-array/
js
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function(nums1, m, nums2, n) {
var i = m - 1
var j = n - 1
var index = m + n - 1
while (i >= 0 && j >= 0) {
nums1[index--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]
}
while (j >= 0) {
nums1[index--] = nums2[j--]
}
}
py
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
i, j, index = m - 1, n - 1, m + n - 1
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[index] = nums1[i]
index -= 1
i -= 1
else:
nums1[index] = nums2[j]
index -= 1
j -= 1
while j >= 0:
nums1[index] = nums2[j]
index -= 1
j -= 1