Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
分析:
这个题和上个题是不一样的,这次数组中每个数都是出现三次,只有一个数出现一次,并且题目要求用线性时间,用O(1)空间,那么这时就不能用暴力的hash方法,或者是排序了,所以要想一个巧妙的方法来解决
可以new一个数组,大小是一个int的大小,count[i]表示所有的数第i为1的个数,如果这个数是3的倍数,直接忽略,如果这个数不是三的倍数,那么其肯定是包含了一个数的值,所以最后只要判断不是3的倍数就可以了
public class Solution {
public int singleNumber(int[] A) {
int w = 4*8;
int[] count = new int[w];
for(int i=0;i<A.length;i++)
for(int j=0;j<w;j++){
count[j]+=(A[i]>>j)&1;
count[j] %= 3;
}
int result = 0;
for(int i=0;i<w;i++){
result += (count[i] << i);
}
return result;
}
}