题目
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?
思路
对于每一位上的数字,统计1的个数。如果1的个数是3n,表明这一位上没有单个数的位。如果1的个数是3n+1,表明这一位上是有单个数的。
最后统计出所有单个数值为1的位,得到数字。
代码1(C++)
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
int i, j;
for(i = 0; i < 32; i ++){
int count = 0;
for(j = 0; j < nums.size(); j ++){
count += (nums[j] >> i) & 1;
}
result |= (count % 3) << i;
}
return result;
}
};
代码2(Python)
用python写,在单个数字为负数的情况下会报错。暂时不知道为啥。
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for i in range(32):
count = 0
for num in nums:
count += (num >> i) & 1
result |= (count % 3) << i
return result