排序后 unique 去重,直接输出个数与升序结果。
OJ: roj
题目 ID: 3544
难度:入门
标签:排序python
创建: 2026-10-02 06:30
更新: 2026-10-06 13:35
题目描述
输入
思路
先 sort 排序,再用 unique 把相邻重复元素去掉,剩余前
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-10-02 06:30
# update_at: 2026-10-02 06:30
import sys
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
n = next(data) # 题面的 N:生成的随机数个数
# 集合推导一次完成"去重",sorted 再完成"排序",O(N log N)
uniq = sorted({next(data) for _ in range(n)})
print(len(uniq)) # 去重后的个数 M
print(*uniq) # 空格分隔的升序结果
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-06 13:35
* update_at: 2026-10-06 13:35
*/
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 105;
int n;
int a[MAXN];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
// 排序后去重:先排序,再用 unique 把相邻重复挤到末尾
sort(a + 1, a + n + 1);
int m = unique(a + 1, a + n + 1) - (a + 1); // 互异元素个数
cout << m << "\n";
for (int i = 1; i <= m; ++i) {
if (i > 1) cout << " ";
cout << a[i];
}
cout << "\n";
return 0;
}