leetcode-88. 合併兩個有序數組

給定兩個有序整數數組 nums1 和 nums2,將 nums2 合併到 nums1 中,使得 num1 成爲一個有序數組。

說明:

初始化 nums1 和 nums2 的元素數量分別爲 m 和 n。
你可以假設 nums1 有足夠的空間(空間大小大於或等於 m + n)來保存 nums2 中的元素。
示例:

輸入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

輸出: [1,2,2,3,5,6]

 

解法1:

插入排序

因爲我剛看了算法第四版裏面的插入排序,插入排序比較適合已經很有序的數組,而此題很符合這個情況,每次都把nums2數組的元素插入到第一個數組裏

時間複雜度是O(n(2m + n) / 2)

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

解法2:

雙指針從前往後,每次比較兩個數組中最前面的那個數,將比較小的數放在目標數組中,最後複製剩下的那個數組。

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] nums1Copy = new int[m];
        System.arraycopy(nums1, 0 ,nums1Copy, 0, m);
        int p1 = 0;
        int p2 = 0;
        int top = 0;
        while(p1 < m && p2 < n){
            if(nums1Copy[p1] < nums2[p2]){
                nums1[top++] = nums1Copy[p1++];
            }else{
                nums1[top++] = nums2[p2++];
            }
        }
        if(p1 < m){
            System.arraycopy(nums1Copy, p1 ,nums1, top, m + n - top);
        }else{
            System.arraycopy(nums2, p2 ,nums1, top, m + n - top);
        }
    }
}

解法3:

雙指針從後往前,每次比較兩個數組中最後面的那個數,將比較小的數放在目標數組中,最後複製剩下的那個數組。節省了一個大小爲m的數組。

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int p1 = m - 1;
        int p2 = n - 1;
        int top = m + n - 1;
        while(p2 >= 0&&p1 >= 0){
            if(nums1[p1] >= nums2[p2]){
                nums1[top--] = nums1[p1--];
            }else{
                nums1[top--] = nums2[p2--];
            }
        }
        if(p2 >= 0){
            System.arraycopy(nums2, 0, nums1, 0, p2 + 1);
        }
    }
}

 

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