88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1and nums2 are m and n respectively.
88.合并有序数组
给定两个有序整型数组nums1和nums2,把nums2合并到nums中成一个有序数组
注意:
你可以假定nums1有足够的空间,也就是说大于等于m+n,能放的下nums2的额外元素。数组nums1和nums2初始化化时各自元素个数是m和n。
思路:很明显的归并。因为最后合并结果要放在nums1中,所以我们不能从头开始归并,这样可能会覆盖nums1的部分元素。所以我们选择从末尾开始归并。因为合并后的长度很好计算,所以只要倒序遍历两个数组,每次取较大的放入归并后数组应该放的位置就行了。
void merge(int* nums1, int m, int* nums2, int n) {
int index = m + n - 1;
int i = m - 1;
int j = n - 1;
while (j >= 0){
if (i < 0) nums1[index--] = nums2[j--];
else nums1[index--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
}
}
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.
"""
index = m + n - 1
i = m - 1
j = n - 1
while j >= 0:
if i < 0:
nums1[index] = nums2[j]
j -= 1
else:
if nums1[i] > nums2[j]:
nums1[index] = nums1[i]
i -= 1
else:
nums1[index] = nums2[j]
j -= 1
index -= 1