website/content.en/ChapterFour/0001~0099/0088.Merge-Sorted-Array.md
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Constraints:
Merge two already sorted arrays, placing the result in the first array, assuming the first array has enough space. The algorithm is required to have sufficiently low time complexity.
To avoid moving a large number of elements, start from the last position of the combined length of the two arrays, repeatedly select the larger number from the two arrays, and place it from the end of the first array toward the beginning. After just one loop, the merged array is generated.
package leetcode
func merge(nums1 []int, m int, nums2 []int, n int) {
for p := m + n; m > 0 && n > 0; p-- {
if nums1[m-1] <= nums2[n-1] {
nums1[p-1] = nums2[n-1]
n--
} else {
nums1[p-1] = nums1[m-1]
m--
}
}
for ; n > 0; n-- {
nums1[n-1] = nums2[n-1]
}
}