剑指Offer 数组中唯一只出现一次的数字
程序员文章站
2022-07-15 10:55:58
...
题目:
在一个数组中除了一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。你可以假设满足条件的数字一定存在。
思考题:
如果要求只使用 O(n) 的时间和额外 O(1) 的空间,该怎么做呢?
样例
输入:[1,1,1,2,2,2,3,4,4,4]
输出:3
解答:
import sys
class Solution(object):
def findNumberAppearingOnce(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
bits = [0] * 32
result = 0
for i in range(len(bits)):
for j in range(len(nums)):
bits[i] += (nums[j] >> i) & 0b1
bits[i] = (bits[i] % 3) << i
result = result | bits[i]
return result
上一篇: 剑指offer-第一次只出现一次的字符