在数组中查找特殊数字
问题内容:
数组中有许多数字,每个数字出现3次,但一个特殊数字出现一次。问题是:如何在数组中找到特殊数字?
现在,我只能提出一些使用基数排序和快速排序的方法,而这些方法无法利用问题的性质。所以我需要其他一些算法。
谢谢你的帮助。
问题答案:
将数字按位添加mod 3,例如
def special(lst):
ones = 0
twos = 0
for x in lst:
twos |= ones & x
ones ^= x
not_threes = ~(ones & twos)
ones &= not_threes
twos &= not_threes
return ones