题目描述
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?
解题思路
因为java里int始终占4个字节,32位。所以我们可以对外层循环遍历32次,然后内层循环记录0-31位每一位出现的次数,内层循环结束后将结果取余于3即为当前位的值。
时间复杂度O(32 * n), 空间复杂度O(1)
代码
public int singleNumber(int[] A) {
int bit, result = 0;
for (int i = 0; i < 32; i++) {
bit = 0;
for (int j = 0; j < A.length; j++) {
if (((A[j] >> i) & 1) == 1) {
bit++;
}
}
bit = bit % 3;
result |= bit << i;
}
return result;
}