标签:
There are two ways for the problem:
1. Tradition: Setup a map or set.
2. Bit operation: x ^ x = 0; so if the number keep XOR, the same ones will cancel each other, the one that left would be the single number.
http://www.programcreek.com/2012/12/leetcode-solution-of-single-number-in-java/
public class Solution {
/**
*@param A : an integer array
*return : a integer
*/
public int singleNumber(int[] A) {
// Write your code here
Map<Integer, Integer> base = new HashMap<Integer, Integer>();
for(int a : A){
if(base.containsKey(a)){
base.put(a, 1);
} else {
base.put(a, 0);
}
}
int result = 0;
for (Map.Entry<Integer, Integer> entry : base.entrySet()){
if (entry.getValue() == 0){
result = entry.getKey();
break;
}
}
return result;
}
}
class Solution {
public:
/**
* @param A: Array of integers.
* return: The single number.
*/
int singleNumber(vector<int> &A) {
// write your code here
int single = 0;
for(int &a : A){
single ^= a;
}
return single;
}
};
标签:
原文地址:http://www.cnblogs.com/codingEskimo/p/5642314.html