我是靠谱客的博主 灵巧未来,这篇文章主要介绍剑指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]

最后

以上就是灵巧未来最近收集整理的关于剑指offer-数组中只出现一次的数字-hashmap-异或-python的全部内容,更多相关剑指offer-数组中只出现一次内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(117)

评论列表共有 0 条评论

立即
投稿
返回
顶部