Find a special number in an array

后端 未结 9 1641
天命终不由人
天命终不由人 2020-12-25 09:07

There are many numbers in an array and each number appears three times excepting for one special number appearing once. Here is the question: how can I find the special numb

9条回答
  •  北海茫月
    2020-12-25 09:45

    Add the numbers bitwise mod 3, e.g.

    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
    

提交回复
热议问题