剑指offer-数组中只出现一次的数字-hashmap-异或-python

hashmap做法

def FindNumsAppearOnce(array):
    # write code here
    candicate = set()
    for element in array:
        if element in candicate:
            candicate.remove(element)
        else:
            candicate.add(element)
    res = []
    while candicate:
        res.append(candicate.pop())
    return res

异或做法

  1. 遍历求整个数组的异或值
  2. 根据这个异或值的第一个为1的位,将数组分成两组,分别遍历求异或
def FindNumsAppearOnce(array):
    # write code here
    xor, num1, num2 = 0
    for element in array:
        xor = xor ^ element
    firstBit1 = 0
    while (xor & 1 == 0) and (firstBit1 <= 32):
        firstBit1 += 1
        xor = xor >> 1

    for element in array:
        classify = element >> firstBit1
        if classify & 1 == 0:
            num1 = num1 ^ element
        else:
            num2 = num2 ^ element
    return [num1, num2]

猜你喜欢

转载自blog.csdn.net/weixin_42766102/article/details/89671529