題目
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 nums1 and nums2 are m and n respectively.
翻譯
假設有兩個已經排序的數組,nums1和nums2。將nums2數組合併到nums1中,合併爲一個排序數組。
注:
你可認爲數組nums1具有足夠的空間用來保存合併到其中的數組2的元素。
思路
如果採取歸併排序中的方式,則需要開闢一個數組。然後從頭遍歷數組,然後歸併。
這裏因爲第一個數組含有足夠的空間,那麼我們可以反其道行之。即從數組nums1和nums2尾部開始歸併。然後將其中的較大值放到nums1尾部。直到歸併結束。
代碼
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int index1 = m-1;
int index2 = n -1;
int pos = m+n-1;
while (index2 >= 0) {
nums1[pos--] = index1 >= 0 && nums1[index1] > nums2[index2] ? nums1[index1--] : nums2[index2--];
}
}
};