[LeetCode] 88. Merge Sorted Array 混合插入有序數組


 

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

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

Output: [1,2,2,3,5,6]

 

混合插入有序數組,由於兩個數組都是有序的,所有只要按順序比較大小即可。題目中說了 nums1 數組有足夠大的空間,說明不用 resize 數組,又給了m和n,那就知道了混合之后的數組的大小,這樣就從 nums1 和 nums2 數組的末尾開始一個一個比較,把較大的數,按順序從后往前加入混合之后的數組末尾。需要三個變量 i,j,k,分別指向 nums1,nums2,和混合數組的末尾。進行 while 循環,如果i和j都大於0,再看如果 nums1[i] > nums2[j],說明要先把 nums1[i] 加入混合數組的末尾,加入后k和i都要自減1;反之就把 nums2[j] 加入混合數組的末尾,加入后k和j都要自減1。循環結束后,有可能i或者j還大於等於0,若j大於0,那么還需要繼續循環,將 nums2 中的數字繼續拷入 nums1。若是i大於等於0,那么就不用管,因為混合數組本身就放在 nums1 中,參見代碼如下:

 

解法一: 

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

 

我們還可以寫的更簡潔一些,將兩個 while 循環融合到一起,只要加上 i>=0 且 nums1[i] > nums2[j] 的判斷條件,就可以從 nums1 中取數,否則就一直從 nums2 中取數,參見代碼如下:

 

解法二:

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

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/88

 

類似題目:

Merge Sorted Array

Merge Two Sorted Lists

Squares of a Sorted Array

Interval List Intersections

 

參考資料:

https://leetcode.com/problems/merge-sorted-array/

https://leetcode.com/problems/merge-sorted-array/discuss/29572/My-simple-solution

https://leetcode.com/problems/merge-sorted-array/discuss/29515/4ms-C%2B%2B-solution-with-single-loop

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM