描述
给出3*n + 1 个的数字,除其中一个数字之外其他每个数字均出现三次,找到这个数字。
样例
给出 [1,1,2,3,3,3,2,2,4,1] ,返回 4
挑战
一次遍历,常数级的额外空间复杂度
思路: 在落单的数1中,我们直接将所有的数异或,那么重复的数就直接去掉了,最后的结果就是那个落单的数。
那么在我们这道题中有两种思路:
1. 还是根据位运算,按位计算。int型数字占32位,如果这个数字出现3次,则与这个数字对应的每一位上的1也出现三次。使用int型数组记录每一位上1出现的次数,能被3整除则表示出现3次。最后得到的就是要求的数字。
2. 可以使用hashmap,当一个数遍历三次后从hashmap中去掉。
Java代码:
1.
public int singleNumber2(int[] A) {
// write your code here
if(A==null || A.length==0){
return 0;
}
int[] bits = new int[32];
int res = 0;
for (int i = 0; i < 32; i++) {
for (int j = 0; j < A.length; j++) {
bits[i] += A[j]>>i & 1;
}
bits[i] = bits[i] % 3;
res = res | bits[i]<<i;
}
return res;
}
2.
public int singleNumberII(int[] A) {
// write your code here
if(A==null || A.length==0){
return 0;
}
Map<Integer, Integer> hashmap = new HashMap<>();
for (int i : A) {
if(hashmap.containsKey(i)){
if(hashmap.get(i)==2){
hashmap.remove(i);
}else{
hashmap.put(i,hashmap.get(i)+1);
}
}else{
hashmap.put(i,1);
}
}
Set<Integer> set = hashmap.keySet();
Iterator<Integer> it = set.iterator();
return it.next();
}