P4305 不重复数字

点击查看代码
#include<bits/stdc++.h>
using namespace std;

const int N=1e5+10,null=0x3f3f3f3f;
int h[N];

int find(int x)
{
    int t=(x%N+N)%N;
    while(h[t]!=null&&h[t]!=x){
        t++;
        if(t==N) t=0;
    }
    return t;
}

int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        memset(h,0x3f,sizeof h);
        vector<int> res;
        for(int i=1;i<=n;i++){
            int x;
            cin>>x;
            int pos=find(x);
            
            if(h[pos]==null) res.push_back(x),h[pos]=x;
        }

        for(int i=0;i<res.size();i++) cout<<res[i]<<" ";
        cout<<endl;
    }

    return 0;
}
简简单单的手写哈希表,非常简单,其实也就是一个find函数罢了,然后注意下N的取值即可
点击查看代码
#include<bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int T;
    cin>>T;
    while(T--){
        int n;
        cin>>n;
        unordered_set<int> st;
        vector<int> res;
        for(int i=1;i<=n;i++){
            int x;
            cin>>x;
            if(st.find(x)==st.end()){
                st.insert(x);
                res.push_back(x);
            } 
        }
        for(int i=0;i<res.size();i++){
            cout<<res[i]<<" ";
        }
        cout<<endl;
    }

    return 0;
}
stl容器的实现方式,很简单。1.定义unordered_set st 2.查找.find()3.插入.insert()4.为空.end()
posted @ 2025-12-04 09:37  AnoSky  阅读(5)  评论(0)    收藏  举报