#6 Merge Two Sorted Arrays

题目描述:

Merge two given sorted integer array A and B into a new sorted integer array.

Example

A=[1,2,3,4]

B=[2,4,5,6]

return [1,2,2,3,4,4,5,6]


题目思路:

two pointers的简单题,就不多说了。

Mycode(AC = 13ms):

class Solution {
public:
    /**
     * @param A and B: sorted integer array A and B.
     * @return: A new sorted integer array
     */
    vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
        // write your code here
        vector<int> ans(A.size() + B.size(), 0);
        
        if (A.size() == 0) return ans;
        
        int idx1 = 0, idx2 = 0, idx = 0;
        
        while (idx1 < A.size() && idx2 < B.size()) {
            if (A[idx1] <= B[idx2]) {
                ans[idx++] = A[idx1++];
            }
            else {
                ans[idx++] = B[idx2++];
            }
        }
        
        while (idx1 < A.size()) {
            ans[idx++] = A[idx1++];
        }
        
        while (idx2 < B.size()) {
            ans[idx++] = B[idx2++];
        }
        
        return ans;
    }
};


阅读更多
版权声明:三千微尘里,吾宁爱与憎 https://blog.csdn.net/haifischxia/article/details/52368387
文章标签: lintcode two pointers
个人分类: lintcode
上一篇#12 Min Stack
下一篇#5 Kth Largest Element
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭