The key is to figure out the %3 … for each bit , and don't forget to & 1 to remove other bits, and shift back… Also int is 32 bits in Java
public class Solution {
public int singleNumber(int[] A) {
int res = 0;
int count = 0;
for (int i=0; i<32; i++){
count = 0;
for (int j=0; j<A.length; j++){
count += ((A[j] >>> i) & 1); //dont forget to & 1 to remove all other bits
}
res = res | ((count % 3) << i); //shift back
}
return res;
}
/*
public int singleNumber(int[] A) {
if(A == null || A.length == 0){
return Integer.MIN_VALUE;
}
Map<Integer, Integer> process = new HashMap<Integer, Integer>();
for(int i = 0; i < A.length; i++){
if(!process.containsKey(A[i])){
process.put(A[i], 1);
}else{
process.put(A[i], process.get(A[i]) + 1);
}
}
Set<Integer> keySet = process.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
int curKey = (Integer)it.next();
if(process.get(curKey) != 3){
return curKey;
}
}
return Integer.MIN_VALUE;
}
*/
}
没有评论:
发表评论