python--剑指offer--中等--56 - II. 数组中数字出现的次数 II
程序员文章站
2022-06-11 18:58:09
...
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ones = twos = 0
for num in nums:
ones = ones ^ num & ~ twos
twos = twos ^ num & ~ ones
return ones
if __name__ == '__main__':
solution = Solution()
nums = [9, 1, 7, 9, 7, 9, 7]
res = solution.singleNumber(nums)
print(res)
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
counts = [0] * 32
for num in nums:
for i in range(32):
counts[i] += num & 1
num >>= 1
res, m = 0, 3
for i in range(31, -1, -1):
res <<= 1
# res += counts[i] % m
res |= counts[i] % m
return res if counts[31] % m == 0 else ~(res ^ 0xffffffff)
if __name__ == '__main__':
solution = Solution()
nums = [9, 1, 7, 9, 7, 9, 7]
nums = [3, 4, 3, 3]
res = solution.singleNumber(nums)
print(res)
上一篇: 力扣20有效的括号题解