给定两个数组,然后将其合并为一个新的数组,要求从小到大排序,并且两个数字中的重复数字要剔除。
思路:
1、设置p1 p2 两个指针分别指向vx vy
2、当p1<x 和p2<y的时候,比较vx[p1]和vy[p2]的大小
3、二者小的一个,res.push_back(),并把对应的指针向后加1
4、碰见俩相等的,不用.push_back, p1, p2直接++
5、多余的部分直接.push_back后面就可以了
#include<iostream>
#include<vector>
using namespace std;
int main() {
int x, y;
int x1, y1;
cin >> x >> y;
vector<int>vx, vy;
int temp;
cout << "输入vx数组" << endl;
for (int i = 0; i < x; i++) {
cin >> temp;
vx.push_back(temp);
}
cout << "vx数组为" << endl;
for (auto x : vx) {
cout << x << " ";
}
cout << endl;
cout << "输入vy数组" << endl;
for (int j = 0; j < y; j++) {
cin >> temp;
vy.push_back(temp);
}
cout << "vy数组为" << endl;
for (auto x : vy) {
cout << x << " ";
}
vector<int> res;
int p1 = 0, p2 = 0;
while (p1 < x && p2 < y) {
if (vx[p1] > vy[p2]) {
res.push_back(vy[p2]);
p2++;
}
else if (vx[p1] < vy[p2]) {
res.push_back(vx[p1]);
p1++;
}
else {
p1++;
p2++;
}
}
while (p1 < x) {
res.push_back(vx[p1]);
p1++;
}
while (p2 < y) {
res.push_back(vy[p2]);
p2++;
}
cout << endl;
cout << "**************************" << endl;
for (auto x : res) {
cout << x << " ";
}
return 0;
}