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;
}
标签:set,cout,int,常见,cin,++,1e5,数组,方法
From: https://www.cnblogs.com/lhycoder/p/17429438.html