问题描述:
总结:利用Hashtable,记录给定数组,并且记录其出现的次数,利用集合类判断结果
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
java代码:
package leetcode11.SingleNumber;
import java.util.Hashtable;
import java.util.Set;
public class Solution {
public static void main(String []args){
int []a={1,1,1,3,2,3,3};
System.out.print(singleNumber(a));
}
public static int singleNumber(int []a){
Hashtable<Integer,Integer>ht =new Hashtable<Integer,Integer>();
for(int i=0;i<a.length;i++){
Integer val=ht.get(a[i]);
if(val!=null){
ht.put(a[i], val+1);
}else
ht.put(a[i], 1);
}
Set<Integer> set=ht.keySet();
for(Integer i:set){
if(ht.get(i)!=3)
return i;
}
return 0;
}
}
总结:利用Hashtable,记录给定数组,并且记录其出现的次数,利用集合类判断结果