#6 Merge Two Sorted Arrays

来源:互联网 发布:chrome mac下载 编辑:程序博客网 时间:2024/06/05 10:14

题目描述:

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;    }};


0 0
原创粉丝点击