题目:
An array of integers, only one integer appears odd times, all others appear even times, find it
Code:
import java.util.*;
class Test{
public static void main(String[] args){
Solution sol = new Solution();
int[] A = {1, 2, 2, 3, 3, 1, 4, 4, 4, 4, 0, 0, 1};
System.out.println(sol.xorOdd(A));
System.out.println(sol.getOdd(A));
}
}
class Solution{
//XOR法
public int xorOdd(int[] A){
if(A==null || A.length==0) return Integer.MIN_VALUE;
int res = 0;
for(int i=0; i<A.length; i++)
res ^= A[i];
return res;
}
//Hashing法
public int getOdd(int[] A){
if(A==null || A.length==0) return Integer.MIN_VALUE;
HashMap<Integer, Boolean> hm = new HashMap<Integer, Boolean>();
for(int i=0; i<A.length; i++){
if(hm.containsKey(A[i])) hm.put(A[i], !hm.get(A[i]));
else hm.put(A[i], true);
}
for(int key : hm.keySet())
if(hm.get(key)) return key;
return Integer.MIN_VALUE;
}
}
Hashing方法自不必说,O(n)的时间和空间复杂度。
XOR的方法,引用一段career-cup上的话:
XOR of a number with itself will give you a 0. 0 XOR'd with any number will give you the same number. Thus an even count of a particular number will give you a 0 while an odd count will give you the number itself.
If you XOR all values one after the other, the even count values will cancel each other out and only the odd count value will remain at the end.
大意是说:0和任何数的XOR都是数本身;数和自己本身的XOR为0。利用这个原理,唯一的一个奇数次出现的数肯定会在一次遍历过后留下,赞!