P761 【入门】明明的随机数
对于一组数据完成完成"去重"与"排序"的工作。
分析
方法1:可以直接排序后去重
点击查看代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 110;
int n, a[N],ans;
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> a[i];
sort(a, a + n);
for (int i = 0; i < n; i++) {
if (i == 0 || a[i] != a[i - 1])
ans++;
}
cout<<ans<<endl;
for (int i = 0; i < n; i++) {
if (i == 0 || a[i] != a[i - 1])
cout << a[i] << " ";
}
return 0;
}
方法2:利用set集合的特性,直接求入set中,再拿出来
点击查看代码
#include <bits/stdc++.h>
#include <set>
using namespace std;
typedef long long LL;
int main() {
int n, x;
set<int> s;
cin >> n;
while (n--) {
cin >> x;
s.insert(x);
}
cout << s.size() << endl;
// 1. 迭代器遍历
set<int>::iterator it = s.begin();
for (; it != s.end(); it++)
cout << *it << " ";
cout << endl;
// 2. for each : -std=C++11
// for (auto u : s) cout << u << " "; cout << endl;
// for (int u : s) cout << u << " "; cout << endl;
return 0;
}