python 三个只出现一次的数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 三个只出现一次的数相关的知识,希望对你有一定的参考价值。

"""
input: numbers
output: 3 number appear once 

solution: ^
"""

import random
from functools import reduce


def findTheLastOne(x):
    return x & (-x)

def findTwoOnceNum(x, s):
    num = findTheLastOne(x)
    a, b = 0, 0
    for i in s:
        if i & num:
            a ^= i
        else:
            b ^= i
    return a, b


def findThreeOnceNum(x, s):
    num = findTheLastOne(x)
    c = 0
    for i in s:
        if i & num:
            c ^= i
    newX = x ^ c
    a, b = findTwoOnceNum(newX, s + [c])
    return a, b, c


def main():
    s = list(range(9)) + list(range(9)) + list(range(10, 13))
    random.shuffle(s)
    print(s, findThreeOnceNum(reduce(lambda x, y: x ^ y, s), s))


if __name__ == "__main__":
    main()

以上是关于python 三个只出现一次的数的主要内容,如果未能解决你的问题,请参考以下文章

数组中只出现一次的数(其它数出现k次)

数组中只出现一次的数

只出现一次的数

只出现一次的数

数组中只出现一次的数(其他数出现k次)

面试题---找出数组中两个只出现一次的数