Using the HashMap and Traverse the entire hashmap to find the value is not equal to 2.
public int singleNumber(int[] A) {
int result = Integer.MIN_VALUE;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i=0; i<A.length; i++) {
if (!map.containsKey(A[i])) {
map.put(A[i], 1);
} else {
map.put(A[i], map.get(A[i]) + 1);
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()) {
if (entry.getValue() != 2) {
result = entry.getKey();
break;
}
}
return result;
}
Another solution is simple and clear but not easy to get it.
public int singleNumber(int[] A) {
int result = A[0];
for (int i=1; i<A.length; i++) {
result ^= A[i];
}
return result;
}
No comments:
Post a Comment