Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution:
思路:
用二进制表示,把第 ith 个位置上所有数字的和对3取余,则只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0). 因此取余的结果就是那个 “Single Number”。
Time Complexity: O(N) Space Complexity: O(32)
Solution Code:
public class Solution {
public int singleNumber(int[] nums) {
int cnt[] = new int[32];
int single = 0;
for (int i = 0; i < 32; i++) {
for (int j = 0; j < nums.length; j++) {
cnt[i] += (nums[j] >> i) & 0x1;
}
single |= cnt[i] % 3 << i;
}
return single;
}
}