# Can you solve the problem using hashtable or hashset?

• I use the hashset to solve the problem, but it caused Time limit exceed,can someone explain why ?Is bit manipulation the only way to accept ?Both two ways need O(n) run time.

``````public class Solution {
public int singleNumber(int[] A) {
HashSet<Integer> set=new HashSet<Integer>();
for(int item:A){
if(set.contains(item)){
set.remove(item);
}
else
}
return set.iterator().next();
}
}``````

I removed my comments to the right place.

• I met the same situation with you. My solution is exactly same to yours. If hashtable causes Time limit issue, why tag shows "Hash table"? Is there any other solutions related to the HashTable but satisfied with time limited?

• Because the exercise asks you to implement it without extra memory. But I am quite curiosity about the"Hash Table" lable of this question

• curiously my HashSet solution was accepted with instantiated an Iterator.

``````public class Solution {
public int singleNumber(int[] A) {
HashSet<Integer> set = new HashSet<Integer>();
Integer num, ans=0;
for(int i=0; i<A.length; i++){
num = new Integer(A[i]);
set.remove(num);
}
}
Iterator setIterator = set.iterator();
if(setIterator.hasNext()){
ans=(Integer)setIterator.next();
}
return ans;
}
} ``````

• hash tables are way too slow (they incur a lot of cache misses). It's faster just to sort the input and run a simple algo on that than it is to do hash lookups.

• I used HashSet and got accepted.
public int singleNumber(int[] nums) {
HashSet<Integer> values = new HashSet<Integer>();
for(int i = 0; i < nums.length; i ++){
if(values.contains(nums[i])) values.remove(nums[i]);