【BZOJ 2761】 不重复数字 (哈希算法)

链接

http://www.lydsy.com/JudgeOnline/problem.php?id=2761

Description

给出N个数,要求把其中重复的去掉,只保留第一次出现的数。
例如,给出的数为1 2 18 3 3 19 2 3 6 5 4,其中2和3有重复,去除后的结果为1 2 18 3 19 6 5 4。

Input

输入第一行为正整数T,表示有T组数据。
接下来每组数据包括两行,第一行为正整数N,表示有N个数。第二行为要去重的N个正整数。

Output

对于每组数据,输出一行,为去重后剩下的数字,数字之间用一个空格隔开。

Sample Input

2
11
1 2 18 3 3 19 2 3 6 5 4
6
1 2 3 4 5 6

Sample Output

1 2 18 3 19 6 5 4
1 2 3 4 5 6

HINT

对于30%的数据,1 <= N <= 100,给出的数不大于100,均为非负整数;
对于50%的数据,1 <= N <= 10000,给出的数不大于10000,均为非负整数;
对于100%的数据,1 <= N <= 50000,给出的数在32位有符号整数范围内。

提示

由于数据量很大,使用C++的同学请使用scanf和printf来进行输入输出操作,以免浪费不必要的时间。

import java.io.*;
import java.util.*;

public class Main {
	static final int N=(int)1e5;
	static final int mod=(int)1e5;
	static int e;
	static void Init() {
		e=0;
		for(int i=0;i<N;i++) head[i]=0;
	}
	static int head[]=new int[N],ans[]=new int[N];
	static class table{
		int val,next;
	};
	static table a[]=new table[2*N];
	static void insert(int u,int v){
		++e;
		if(a[e]==null) a[e]=new table();
        a[e].next=head[u];
		head[u]=e;
		a[e].val=v;
	}
	static boolean add(int x){
		int sum=0,t=x;
		if(t<0)t=-t;
		while(t>0){
			sum=sum*3+(t%10)%mod;
			t/=10;
		}
		for(int i=head[sum];i!=0;i=a[i].next)
			if(a[i].val==x) return true;
		insert(sum,x);
		return false;
	}
	public static void main(String[] args){
		Scanner sc=new Scanner(new InputStreamReader(System.in));
		int T=sc.nextInt();
		
		while(T--!=0){
            Init();
			int n=sc.nextInt();
			StringBuilder ans=new StringBuilder("");
			boolean first=true;
			for(int i=0;i<n;i++)
			{
				int x=sc.nextInt();
				if(!add(x)){
					if(!first) ans.append(" ");
					else first=false;
					ans.append(x);
				}	
			}
			System.out.println(ans);
		}
		sc.close();
	}
}
原文地址:https://www.cnblogs.com/zsyacm666666/p/7228626.html