合並兩個有序數組到其中一個數組中


題目描述

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

解法一:

從結尾開始歸並,不會覆蓋元素。從A[n+m-1]處開始往前一個元素一個元素的求,每次都要比較A[i]和B[j]的大小。

需要注意的是,要考慮到: A和B有一個為空時的情況

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int i , j , k ;
        for( i = m - 1, j = n - 1, k = n + m -1; k >= 0; --k)
        {
            if( i >= 0 &&(j < 0 || A[i] >= B[j]) )
            
                A[k] = A[i--];
            else            
                A[k] = B[j--];  
        }
    }
};

解法二:

算法思想是:由於合並后A數組的大小必定是m+n,所以從最后面開始往前賦值,先比較A和B中最后一個元素的大小,把較大的那個插入到m+n-1的位置上,再依次向前推。如果A中所有的元素都比B小,那么前m個還是A原來的內容,沒有改變。如果A中的數組比B大的,當A循環完了,B中還有元素沒加入A,直接用個循環把B中所有的元素覆蓋到A剩下的位置。代碼如下:

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int count = m + n - 1;
        --m; --n;
        while (m >= 0 && n >= 0) A[count--] = A[m] > B[n] ? A[m--] : B[n--];
        while (n >= 0) A[count--] = B[n--];
    }
};

 

 


免責聲明!

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



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