LeetCode筆記: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.

大意:

給出兩個(gè)排序好了的整型數(shù)組 nums1 和 nums2,將 nums2 合并到 nums1 中去成為一個(gè)排好序的數(shù)組。
注意:
你可以假設(shè) nums1 有足夠的空間(尺寸大于等于 m + n)來添加從 nums2 來的額外的元素。nums1 和 nums2 中的元素個(gè)數(shù)分別為 m 和 n。

思路:

這道題一開始并不想用最直接最笨的方法做,而是試圖利用題目的條件來做。題目?jī)蓚€(gè)原本的數(shù)組都是排好序了的,題目沒有返回值,因此只能在nums1中直接操作,不能放新的數(shù)組,題目額外給出了元素個(gè)數(shù)m和n,這都是暗示。不過最終也沒做好,后來發(fā)現(xiàn)其實(shí)還是思路方向反了= =

這里先說最直接的辦法,空間換時(shí)間,直接創(chuàng)建一個(gè)新數(shù)組,然后一個(gè)個(gè)從兩個(gè)數(shù)組中按照順序拿元素去比較大小放回nums1中,就得到一個(gè)排好序的數(shù)組了。

代碼(Java):

public class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if (nums2.length == 0) return;
        
        int[] nums = Arrays.copyOfRange(nums1, 0, m);
        int i = 0;
        int j = 0;
        int k = 0;
        while (i < nums.length && j < nums2.length) {
            if (nums[i] <= nums2[j]) {
                nums1[k] = nums[i];
                i++;
            } else {
                nums1[k] = nums2[j];
                j++;
            }
            k++;
        }
        while (i < nums.length) {
            nums1[k] = nums[i];
            i++;
            k++;
        }
        while (j < nums2.length) {
            nums1[k] = nums2[j];
            j++;
            k++;
        }
        
        return;
    }
}

他山之石:

public 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--];
        
        return;
    }
}

這個(gè)做法讓我明白我的思路還是反了,之前一直想的還是順序去找元素,還在想怎么處理原來位置的元素,這個(gè)方法直接從后面開始排,先放最后面的數(shù),從大到小慢慢往前走,放的數(shù)一定不會(huì)覆蓋原來nums1中的數(shù),因?yàn)橛凶銐虻奈恢谩H绻鹡ums2中的數(shù)先放完,那么剩下的nums1前面的數(shù)位置不用動(dòng),如果nums1的先放完,剩下還有一些nums2的數(shù)就直接放在前面去了。

此外,這里為了精簡(jiǎn)代碼,使用了i--這種先取值然后減一的特性。

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容