【Leetcode】 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 nums1 and nums2 are m and n respectively.

翻譯: 
給定2個排序好的整數數組nums1和nums2,把nums2合併到nums1中成爲1個排序的數組。 
提示:你可以假定nums1有足夠的空間(大小>=m+n)來容納來自nums2的額外的元素。nums1和nums2的元素的個數各自被初始化爲m和n。

分析: 
1. 如果nums1從前往後遍歷的話,nums2中的元素需要插入nums1,這個時候每插入一次,就會需要將nums1的元素往後移動(或者需要申請額外的存儲空間)。但是我們反過來想,由於合併後的數組長度是確定的,我們可以從最大的數開始寫入,這個時候由於nums1的後面部分的空間是未使用的,剛好可以直接覆寫。 
2. 需要考慮比較特殊的情況,就是數組可能爲空。2個數組都爲空自然進不去循環。但是其中一個爲空,就要考慮數組可能發生越界的情況了。並且兩個數組都是排好序的,更加方便我們排序。

Java版本:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m - 1, j = n - 1, k = m + n -1;
        while (i > -1 && j > -1) nums1[k--] = (nums1[i]>nums2[j]) ? nums1[i--] : nums2[j--];
        while (j > -1) nums1[k--] = nums2[j--];
    }
}
注意此處,由於假設nums1是足夠大的,即使nums2中的元素全大於nums1,由於從後往前添加,nums1 仍然可以保持不變。所以不需要再判斷nums1中原有元素索引是否過界。

即假若nums2中j個元素全遍歷完後,nums1中剩餘的元素只需要保持原有位置即可,不用再排序。但若nums1中原有i個元素遍歷完後,新數組前面的元素與後面的元素是有重複的,nums2中剩餘的元素還需要依次替換掉之前nums1中前面索引座標的元素。

Python版本:

def merge(self, nums1, m, nums2, n):
        while m > 0 and n > 0:
            if nums1[m-1] >= nums2[n-1]:
                nums1[m+n-1] = nums1[m-1]
                m -= 1
            else:
                nums1[m+n-1] = nums2[n-1]
                n -= 1
        if n > 0:
            nums1[:n] = nums2[:n]

C++版本:

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = m - 1, j = n - 1, tar = m + n - 1;
        while (j >= 0) {
            nums1[tar--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--];
        }
    }
};





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章