Merge two given sorted integer array A and B into a new sorted integer array.
Have you met this question in a real interview?
Yes
Example
A=
[1,2,3,4]
B=
[2,4,5,6]
return
[1,2,2,3,4,4,5,6]
Challenge
其实就是merge sort....衍生出很多有意思的题来,当然,这题是最无聊。。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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> res; int begA=0, begB=0; while(begA<A.size()&& begB<B.size()){ if (A[begA]<B[begB]){ res.push_back(A[begA++]); } else{ res.push_back(B[begB++]); } } while(begA<A.size()){ res.push_back(A[begA++]); } while(begB<B.size()){ res.push_back(B[begB++]); } return res; } }; |
No comments:
Post a Comment