C++数组去重的方法

一、使用桶(会排序)

        

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, a[N];
int t[N];   //  建立一个桶 
int max_num = 0x80000000;   //  打擂台,求最大出始值为最小 
int main()
{
	cin >> n;
	for(int i=1;i<=n;i++)
	{
		cin >> a[i];
		max_num = max(max_num, a[i]);   //  求最大值(桶的边界) 
		t[a[i]]++;   //  将数存入桶  
	}
	for(int i=1;i<=n;i++)
	{
		if(t[i] != 0)
		{
			cout << i << " ";
		}
	}
	return 0;
}

运行结果:

5
1 1 2 2 3
1 2 3
5
3 2 2 1 1
1 2 3

二、使用函数(不会排序)

        

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, a[N];
int main()
{
	cin >> n;
	for(int i=0;i<n;i++)
	{
		cin >> a[i];
	}
	int k = unique(a, a + n) - a;
	for(int i=0;i<k;i++)
	{
		cout << a[i] << " "; 
	}
	return 0;
}

运行结果:

5
1 1 2 2 3
1 2 3
5
3 2 2 1 1
3 2 1
如果想加排序就在第十二行上加一个:
sort(a, a + n);

三、使用set去重(会排序)

        

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
set<int> st;
int n, a[N];
int main()
{
	cin >> n;
	for(int i=1;i<=n;i++)
	{
		cin >> a[i];
		st.insert(a[i]); 
	}
	for(set<int>::iterator i = st.begin();i!=st.end();i++)
	{
		cout << *i << " ";
	}
	return 0;
}

好了,以上就是本蒟蒻总结的c++的去重方法,如果有问题欢迎大佬们在评论区里更正。

                                    感谢观看!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值