6、合併排序數組 ||

題目要求:

合併兩個排序的整數數組A和B變成一個新的數組。

樣例
給出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]

挑戰
你能否優化你的算法,如果其中一個數組很大而另一個數組很小?

 

代碼實現:

使用vector、和其中的push_back函數

class Solution {
public:
    /**
     * @param A: sorted integer array A
     * @param B: sorted integer array B
     * @return: A new sorted integer array
     */
    vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) 
    {
        // write your code here
        vector<int> C;   //定義vector動態數組
        int i = 0, j = 0;
        while(i<A.size() && j<B.size())
        {
            if(A[i]<B[j])
            {
                C.push_back(A[i++]);  //在vector數組末尾插入新元素
            }                         //++在後,得到遞增之前的結果;++在前,得到遞增之後的結果
            else
            {
                C.push_back(B[j++]);
            }
        }
        while(i<A.size())
        {
            C.push_back(A[i++]);
        }
        while(j<B.size())
        {
            C.push_back(B[j++]);
        }
        return C;
    }
};

補充知識點:https://www.cnblogs.com/yskn/p/9053161.html

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