137. Single Number II
Problem
Every value in nums appears three times except one, which appears once. Return that one, in O(n) time and O(1) extra space.
Example: [2,2,3,2] → 3; [0,1,0,1,0,1,99] → 99
Every other number appears 3 times → for each bit position, the count of set bits mod 3 is the single number's bit. (Handle the sign bit for negatives in Python.)
Complexity: O(32·n).
class Solution:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for b in range(32):
if sum((x >> b) & 1 for x in nums) % 3:
res |= 1 << b
return res - (1 << 32) if res >= 1 << 31 else res
assert Solution().singleNumber([2, 2, 3, 2]) == 3
assert Solution().singleNumber([0, 1, 0, 1, 0, 1, 99]) == 99
assert Solution().singleNumber([-2, -2, 1, 1, 4, 1, 4, 4, -4, -2]) == -4
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for (int b = 0; b < 32; b++) {
int cnt = 0;
for (int x : nums) cnt += (x >> b) & 1;
if (cnt % 3 != 0) res |= 1 << b;
}
return res;
}
}
func singleNumber(nums []int) int {
res := 0
for b := 0; b < 32; b++ { // each bit's count mod 3 is the single number's bit
cnt := 0
for _, x := range nums {
cnt += (x >> b) & 1
}
if cnt%3 != 0 {
res |= 1 << b
}
}
return int(int32(res)) // bit 31 is the sign of a 32-bit int
}