Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a special number in an array

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 number in the array?
Now I can only put forward some methods with radix sorting and rapid sorting which cannot takes advantage the property of the question. So I need some other algorithms.
Thanks for your help.

like image 211
jerry_sjtu Avatar asked Dec 09 '25 01:12

jerry_sjtu


1 Answers

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
like image 57
user635541 Avatar answered Dec 11 '25 12:12

user635541