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
Tags
Related Problems
一个很简单的题目,由于对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 herevector<int> result;int i,j,k;i=j=k=0;while(i<A.size()&&j<B.size()){if(A[i]<=B[j]){result[k++]=A[i++];}else{result[k++]=B[j++];}}while(i<A.size()){result[k++]=A[i++];}while(j<B.size()){result[k++]=B[j++];}return result;}
};
测试报Runtime error,观察了很久,发现原来是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 herevector<int> result(A.size()+B.size(),0);int i,j,k;i=j=k=0;while(i<A.size()&&j<B.size()){if(A[i]<=B[j]){result[k++]=A[i++];}else{result[k++]=B[j++];}}while(i<A.size()){result[k++]=A[i++];}while(j<B.size()){result[k++]=B[j++];}return result;}
};
或者如果不对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 herevector<int> result;int i,j,k;i=j=k=0;while(i<A.size()&&j<B.size()){if(A[i]<=B[j]){result.push_back(A[i++]);}else{result.push_back(B[j++]);}}while(i<A.size()){result.push_back(A[i++]);}while(j<B.size()){result.push_back(B[j++]);}return result;}
};