LeetCode 88. Merge Sorted Array

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

我的做法:直接將 nums2 拼接在 nums1 數組後面,然後重新排序。這種做法雖然滿足要求,但是不符合算法的思想。

public void merge(int[] nums1, int m, int[] nums2, int n) {
    for(int i = 0; i < n; i++){
        nums1[m + i] = nums2[i];
    }
    Arrays.sort(nums1);      
}

符合算法思想的做法:從 nums1 的後面向前填充數據, while 的判斷條件應判斷 j 是否 > 0,而不是 i ,因爲最終合併的數組放在 nums1 中,若 nums2 數組中沒有元素,則什麼都不需要做。

public void merge1(int[] nums1, int m, int[] nums2, int n) {
    int i = m - 1;
    int j = n - 1;
    int k = m + n - 1;
    while(j >= 0){
        if(i >= 0 && nums1[i] > nums2[j]){                      
            nums1[k] = nums1[i];
            k--;
            i--;
        }
        else{
            nums1[k] = nums2[j];
            k--;
            j--;
        }
    }       
}
發佈了48 篇原創文章 · 獲贊 11 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章