Welcome to LHY's Blog!

对数组去重的常见方法

1. 排序 + 去重

方法一:unique + sort

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

int n;
int a[N];

int main()
{
	cin >> n;
	for (int i = 0; i < n; i ++ ) cin >> a[i];
	
	//排序 + 去重 
	sort(a, a + n);
	n = unique(a, a + n) - a;
	
	for (int i = 0; i < n; i ++ ) cout << a[i] << " " << endl;
	
	return 0;
}

方法二:set

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

int n;
int a[N];

int main()
{
	cin >> n;
	for (int i = 0; i < n; i ++ ) cin >> a[i];
	
	//排序 + 去重
	set<int> s;
	for (int i = 0; i < n; i ++ ) s.insert(a[i]);
	
	for (auto x : s) cout << x << ' ';
	
	return 0;
}

2. 保序 + 去重

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

int n;
int a[N];

int main()
{
	cin >> n;
	for (int i = 0; i < n; i ++ ) cin >> a[i];
	
	//保序 + 去重  
	unordered_set<int> s;
	int k = 0;
	for (int i = 0; i < n; i ++ )
		if (s.insert(a[i]).second)
			a[k ++ ] = a[i];
	n = k;
	
	for (int i = 0; i < n; i ++ ) cout << a[i] << ' ';
	
	return 0;
}
posted @ 2023-05-24 20:29  LiHaoyu  阅读(121)  评论(0)    收藏  举报