P4305 不重复的数字

https://www.luogu.org/problemnew/show/P4305

思路:构造哈希表,然后一边输入一边判断输入的数字在哈希表中是否存在,若没有存在就输出这个数,不存在就读入下一个数字 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int k=52453;  //质数
struct ha
{
	int data;
	int  status;
	ha():status(-1), data(-1){};
};
ha hashtable[k];


bool  locate(int x)
{
	int position = x % k;//第一个位置
	int temp = position;
	if(hashtable[position].status == -1)//第一个位置就符合x去放
	{
		hashtable[position].data = x;
		hashtable[position].status = 1;
		return true;
	}
	while(hashtable[position].status != -1 && hashtable[position].data != x )
	{
		//如果一直冲突查找下一个位置
		position = (position + 1) % k;
		if(position == temp)//表满了
			break;
	}
	if(hashtable[position].status == -1)//找到空的位置
	{
		hashtable[position].data = x;
		hashtable[position].status =1;
		return true;
	}
	if(hashtable[position].data == x)//找到x存在
		return false;
	if(position == temp)//表满了
		return true;
}
int main()
{
	ios::sync_with_stdio (false);
	int t;
	scanf("%d", &t);
	while(t--)
	{
		for(int i = 0; i <k; i++)//重置
		{
			hashtable[i].status = -1;
			hashtable[i].data = -1;
		}
		int x;
		int n;
		scanf("%d", &n);
		for(int i = 0; i < n; i++)
		{
			scanf("%d", &x);
			if(locate(x))//如果没有出现过
				cout<<x<<" ";
		}
		cout<<endl;

	}
	//system("pause");
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值