合并两个有序升序的整数数组A和B变成一个新的数组。新数组也要有序
样例 1:
输入: A=[1], B=[1]
输出:[1,1]
样例解释: 返回合并后的数组
样例 2:
输入: A=[1,2,3,4], B=[2,4,5,6]
输出: [1,2,2,3,4,4,5,6]
样例解释: 返回合并后的数组。
方法1:
功能实现
class Solution {
public:
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
// write your code here
int len1=A.size();
int len2=B.size();
int len = len1+len2;
A.resize(len);
for(int i=0;i<len2;i++){
A[len1+i]=B[i];
}
sort(A.begin(),A.end());
return A;
}
};
void Display1(vector<int>&C){
vector<int> :: iterator it =C.begin();
while(it != C.end()){
cout << *it << " ";
it++;
}
cout << endl;
}
void Display2(vector<int>&V){
int len=V.size();
for(int i=0;i<len;i++){
cout << V[i] << " ";
}
cout << endl;
}
void Display3(int a)
{
cout<<a<<" ";
}
void Display4(vector<int> a)
{
for(int i=0;i<a.size();i++){
cout<<a[i]<<" ";
}
}
功能测试
int main(){
vector<int> A;
vector<int> B;
A.push_back(1);
A.push_back(2);
A.push_back(4);
A.push_back(5);
A.push_back(7);
B.push_back(4);
B.push_back(6);
B.push_back(8);
B.push_back(9);
B.push_back(10);
Solution s;
A=s.mergeSortedArray(A,B);
for_each(A.begin(),A.end(),Display3);
cout << endl;
Display1(A);
Display2(A);
Display4(A);
return 0;
}
方法2:
功能实现
class Solution1{
public:
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
// write your code here
int len1=A.size();
int len2=B.size();
int len = len1+len2;
vector<int> C;
C.resize(len);
for(int i=0;i<len;i++){
if(i<len1){
C[i]=A[i];
}
else{
C[i]=B[i-len1];
}
}
sort(C.begin(),C.end());
return C;
}
};
功能测试
int main(){
vector<int> A;
vector<int> B;
A.push_back(1);
A.push_back(2);
A.push_back(4);
A.push_back(5);
A.push_back(7);
B.push_back(4);
B.push_back(6);
B.push_back(8);
Solution1 s;
vector<int> C;
C=s.mergeSortedArray(A,B);
for_each(C.begin(),C.end(),Display3);
return 0;
}