跳到正文

题解

不重复数字

zzr8178541919约 3 分钟
原文
文章信息与版本

文章信息

发布
2019年11月3日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 3 分钟
获赞
1
题目
P4305

版本

  1. v1当前

hash的模板题

Hash算法是什么呢,可以理解为他就是对桶的一种优化。能够在合理的空间范围内计算出每个值是否出现过。

怎么完成Hash的操作呢

首先需要一个mod,用来取模。就是为了防止空间太大。通常mod取素数

C++
const int mod=100003;

核心就是一个Find函数,找到一个空的位置。

C++
int Find(int x)
{
	int res=x%mod;
	while(hash[res] && hash[res]!=x)
	res=(res+1)%mod;
	return res;
}

我们需要一个函数来判断数x是否已经出现过。

C++
bool check(int x)
{
	if(hash[find(x)]==x)
	return true;
	return false;
}

还需要一个函数用来加入Hash表

C++
void add(int x)
{
	hash[find(x)]=x;//建立映射的关系。 
}

它们整体组成了hash表,每次访问了一个数,放进去判断一下就行了。

完整代码:

C++

//hash的模板题。
//类似于桶,在桶的基础上优化了空间。 

#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
using namespace std;
int hash1[200005];//hash数组记录的是x这个数对应的值是哪个 
const int mod=100003;
inline int read()
{
	int x=0;
	int f=1;
	char ch=getchar();
	while(ch>'9' || ch<'0')
	{
		if(ch=='-')
		f=-1;
		ch=getchar();
	}
	while(ch<='9' && ch>='0')
	{
		x=x*10+ch-'0';
		ch=getchar();
	}
	return x*f;
}
int Find(int x)//Find数组找的是能够储存x第一个位置。 
{
	int res;
	if(x<0)
	res=-x%mod;
	else
	res=x%mod;
	while(hash1[res] && hash1[res]!=x)
	res=(res+1)%mod;
	return res;
}
void push(int x)
{
    hash1[Find(x)]=x;//先找到x对应的值,然后用hash1记录下来
}	
bool check(int x)
{
	if(hash1[Find(x)]==x)//如果 
	return true;
	return false;
}
int main()
{
	int T;//有T组数据 
	T=read();
	while(T--)
	{
		memset(hash1,0,sizeof(hash1));//将hash数组清零。 
		int n=read();//读入个数, 
		for(int i=1;i<=n;i++)
		{
			int x=read();//输入。 
			if(check(x))//如果这个数在hash表中找到了,那么久continue 
			continue;
			printf("%d ",x);//否则就输出, 
			push(x);//再把x加入到hash表中。 
		}
		cout<<endl;
	}
	return 0;
}
原文