剑指offer 数组中只出现一次的数字 python

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了偶数次。请写程序找出这两个只出现一次的数字。

样例

返回[a,b]

想法一:
通常想法,使用HashMap,两边遍历。

class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        dict = {}
        list = []
        Counter
        for i in array:
            if i in dict:
                dict[i] += 1
            else:
                dict[i] = 1
        for key, value in dict.items():
            if value == 1:
                list.append(key)
        return list

想法二:
思路与一相同,但是想使用python的函数式编程,但是自己想了半天也没有做出来,之后看了讨论区,发现有Counter数据结构,对于这个问题就很简单了。

class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        return list(map(lambda x: x[0], Counter(array).most_common()[-2:]))

想法三:
使用位运算,两个相同的数异或之后为0,所以遍历数组,两两异或之后必定会且至少有一位为1,那么就找到那个1的位置,说明在这一位上这两个数是不相同的,那么再遍历一遍,每个数都移位,判断该位置是否为1,如果是1就与一个数异或,如果不是就与另一个数异或,最后便会得到两个唯一的数

class Solution:
    def FindNumsAppearOnce(self, array):
        if not array:
            return []
        # 对array中的数字进行异或运算
        sum = 0
        for i in array:
            sum ^= i
        index = 0
        while (sum & 1) == 0:
            sum >>= 1
            index += 1
        a = b = 0
        for i in array:
            if self.fun(i, index):
                a ^= i
            else:
                b ^= i
        return [a, b]
    def fun(self, num, index):
        num = num >> index
        return num & 1

最后

刷过的LeetCode或剑指offer源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
有任何问题可以在下面评论或者通过私信或联系方式找我。
联系方式
QQ:791034063
Wechat:liuyuhang791034063
CSDN:https://blog.csdn.net/Sun_White_Boy
Github:https://github.com/liuyuhang791034063

posted @ 2018-10-11 17:33  GF66  阅读(1306)  评论(0编辑  收藏  举报