不重复数字(hash)

在这里插入图片描述
自己总过60%,不得其解,参考大佬的代码,若有所思,加了注解。太强大了

#include <bits/stdc++.h>
using namespace std;
const int P=50000;
struct node
{
    
    
    int v,nxt;
} rec[10+P];
int hd[10+P],n,tot;
int H(int x)
{
    
    
    return (x%P+P)%P;
}
bool add(int x, int v)
{
    
    
    for (int i=hd[x];            i;                  i=rec[i].nxt)
///   可以减少不必要的判断   若i==0,直接返回ture   向前一个已存的数
        if (rec[i].v==v)///之前已经出现过
            return false;
    rec[++tot].v=v;///记录已出现过的数字
    rec[tot].nxt=hd[x];
    hd[x]=tot;/// tot:记录个数
    return true;
}
int main()
{
    
    
    int T;
    scanf("%d",&T);
    while(T--)
    {
    
    
        memset(rec,0,sizeof rec);
        memset(hd,0,sizeof hd);
        scanf("%d",&n);
        tot=0;
        while (n--)
        {
    
    
            int x;
            scanf("%d",&x);
            if (add(H(x),x))
                printf("%d ",x);
        }
        puts("");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/cuijunrongaa/article/details/106099927
今日推荐