题解
2025-12-28 19:48:25
发布于:浙江
3阅读
0回复
0点赞
虽然是 的题,但是刚学完哈希表。
题目描述挺清楚的了,不多赘述。
思路:
用哈希表去做。如果这个数已经在哈希表中,跳过;否则把这个数加入哈希表。注意需要排序,所以在加入哈希表的时候也放到一个数组里。到时候排完序输出就行。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N=1e7+19;
vector<int> v;
struct Hash{//从洛谷顺的模版,忘了是谁的了。内容是拉链法哈希表。后序会自己写板子
int h[N]; //哈希表
int e[N],ne[N],idx=0; //这是链表的东西
void insert(int x){ //插入一个数x
int k=(x%N+N)%N; //k是x对应的哈希值
e[idx] = x;
ne[idx] = h[k];
h[k] = idx ++; //链表的基本操作
return;
}bool find(int x){ //查找x
int k=(x%N+N)%N; //计算x的哈希值
for(int i=h[k];i!=-1;i=ne[i])
if(e[i]==x)return true; //如果找到了,返回true
return false; //遍历完了都没找到,返回false
}void init(){
memset(h,-1,sizeof h); //初始化,让h中的初始值都为-1
return;
}
};
long long read(){
long long x=0,f=1;
long long ch=getchar();
while(ch<'0' or ch>'9'){
if(ch=='-')f=-1;
ch=getchar();
}while(ch>='0' and ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);
ch=getchar();
}return x*f;
}
void write(long long x){
if(x==0){
putchar('0');
return ;
}
if(x<0){
putchar('-');
x=-x;
}if(x>9)write(x/10);
putchar(x%10+'0');
}
int main(){
Hash a;
int n;
n=read();
a.init();
int ans=0;
while(n--){
int x;
x=read();
if(a.find(x))continue;
else{
ans++;
v.push_back(x);
a.insert(x);
}
}sort(v.begin(),v.end());
write(ans);
putchar('\n');
for(auto i:v){
write(i);
putchar(' ');
}
return 0;
}
这里空空如也







有帮助,赞一个