C++中合并两个数组,并去除重复数字(无论有没有顺序)

给定两个数组,然后将其合并为一个新的数组,要求从小到大排序,并且两个数字中的重复数字要剔除。

思路:

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;
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值