Description
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]
Challenge
How can you optimize your algorithm if one array is very large and the other is very small?
题目模板
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,让你把这两个数组的数按从小到大的顺序合并到一个不定长数组vector里。
大概思路
题目很简单,和数据结构指针那一章的课后习题一样。需要注意的就是当一个数组读到尾的时候,另一个数组可能还有数据,最后需要判断下。
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> after; int a = 0, b = 0; int lena = A.size(), lenb = B.size(); while(a != lena && b != lenb){ if(A[a] < B[b]) after.push_back(A[a++]); else after.push_back(B[b++]); } if(a == lena) for(; b<lenb; b++) after.push_back(B[b]); if(b == lenb) for(; a<lena; a++) after.push_back(A[a]); return after; } };
题目链接:https://www.lintcode.com/problem/merge-two-sorted-arrays/description