Given a non-empty 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?
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
public class Solution {
public int singleNumber(int[] nums) {
int[]count = new int[32];
int rst = 0;
for(int i=0; i<32; i++){
for(int j=0; j<nums.length; j++)
count[i] += (nums[j] >> i) & 1;
rst |= ((count[i] % 3)<<i);
}
return rst;
}
}
https://cloud.tencent.com/developer/article/1131945
public int singleNumber(int[] A) {
int ones = 0, twos = 0;
for(int i = 0; i < A.length; i++){
ones = (ones ^ A[i]) & ~twos;
twos = (twos ^ A[i]) & ~ones;
}
return ones;
}
这个时候Python就比较尴尬了,需要判断第32位上面是不是1,如果是1,说明是负数,结果要减去2**32
class Solution:
def singleNumber(self, a):
"""
:type nums: List[int]
:rtype: int
"""
count=[0]*32
for i in a:
for j in range(32):
count[j] += (i>>j) & 1
res=0
for i,v in enumerate(count):
if v%3==1:
res+=(1<<i)
return res if res<=2**31-1 else res-2**32
print(Solution().singleNumber([2,2,3,2]))
print(Solution().singleNumber([-2,-2,1,1,-3,1,-3,-3,-4,-2]))
print(2**31)