进制: 找出那个掉单的元素(OddManOut)

2018-09-27  本文已影响4人  极光火狐狸

python

# -.- coding:utf-8 -.-
# 在乱序的数字列表中, 每个数字都会出现两次,
# 但其中有一个数字是只出现一次的, 现在需要
# 找出那个掉单的数字!
from __future__ import print_function


def odd_man_out_onlogn(values):
    """
    如果是我来写, 那么将会是这个代码,
    速度估计是O(nlognnnnnnn)
    """
    s = {}
    result = 0
    for value in values:
        if not s.get(value):
            s[value] = 0
        s[value] += 1

    for i in s:
        if s[i] == 1:
            result = i

    return result


def odd_man_out_on(values):
    """
    速度: O(n)
    空间: O(n)
    """
    s = set()
    total = 0
    for value in values:
        if value in s:
            total -= value
        else:
            s.add(value)
            total += value
    return total


def odd_man_out_o1(values):
    """
    速度: O(n)
    空间: O(1)
    """
    mask = 0
    for value in values:
        mask ^= value
    return mask


def debug_odd_man_out(values):
    """
    打印日志分析为什么可以找出这个单一的数字!
    """
    mask = 0
    for value in values:
        before = mask
        print("mask:  ", bin(mask)[2:].zfill(8))
        print("value: ", bin(value)[2:].zfill(8))
        mask ^= value
        print("xor:   ", bin(mask)[2:].zfill(8))
        print("result: {} xor {} == {}".format(before, value, mask))
        print("\n"*3)
    return mask


def main():
    values = [5, 1, 2, 3, 0, 1, 4, 2, 5, 0, 3]
    print(odd_man_out_onlogn(values))
    print(odd_man_out_on(values))
    print(odd_man_out_o1(values), end="\n"*3)

    print(debug_odd_man_out(values))


if __name__ == '__main__':
    main()

# output
4
4
4


mask:   00000000
value:  00000101
xor:    00000101
result: 0 xor 5 == 5




mask:   00000101
value:  00000001
xor:    00000100
result: 5 xor 1 == 4




mask:   00000100
value:  00000010
xor:    00000110
result: 4 xor 2 == 6




mask:   00000110
value:  00000011
xor:    00000101
result: 6 xor 3 == 5




mask:   00000101
value:  00000000
xor:    00000101
result: 5 xor 0 == 5




mask:   00000101
value:  00000001
xor:    00000100
result: 5 xor 1 == 4




mask:   00000100
value:  00000100
xor:    00000000
result: 4 xor 4 == 0




mask:   00000000
value:  00000010
xor:    00000010
result: 0 xor 2 == 2




mask:   00000010
value:  00000101
xor:    00000111
result: 2 xor 5 == 7




mask:   00000111
value:  00000000
xor:    00000111
result: 7 xor 0 == 7




mask:   00000111
value:  00000011
xor:    00000100
result: 7 xor 3 == 4




4

 
 

rust

fn example(x: &[i32]) -> i32 {
    let mut mask : i32 = 0;
    for i in x {
        mask ^= *i;
    }
    mask
}

fn main() {
    println!("main: {}", example(&[5, 1, 2, 3, 0, 1, 4, 2, 5, 0, 3]));
}
上一篇下一篇

猜你喜欢

热点阅读