题目描述
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input: nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
解题思路
这个题我们可以从后往前遍历2个数组, 将大的值覆盖到nums1的尾部, 依次往前, 当nums1遍历完, nums2没有的时候, 直接把nums2剩余的拼接到nums1, 这个过程与归并排序的归并过程类似
示例代码
func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
var idxM = m - 1
var idxN = n - 1
while idxN >= 0 && idxM >= 0 {
let lastM = nums1[idxM]
let lastN = nums2[idxN]
let index = idxM+idxN+1
if lastM > lastN {
nums1[index] = lastM
idxM -= 1
}else {
nums1[index] = lastN
idxN -= 1
}
}
if idxN >= 0 {
nums1[0...idxN] = nums2[0...idxN]
}
}