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

40.数组中只出现一次的数字

题目描述

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

记录

方法一:
字典

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        if not array:
            return
        res = []
        dict = {}
        for i in array:
            if i not in dict:
                dict[i] = 1
            else:
                dict[i] += 1
        for k,v in dict.items():
            if v == 1:
                res.append(k)
        return res

方法二:

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        if not array:
            return []
        res = []
        for i in array:
            if i in res:
                res.remove(i)
            else:
                res.append(i)
        return res

备注:还有使用count或者Counter的就不赘述了。

方法三:
异或:一个数与自己异或为0,一个数与0异或为自己。

实例:[2,4,3,6,3,2,5,5]

第一步:全数组异或。

		res = 0
        #第一步:全数组异或
        for i in array:
            res ^= i

数组中其他的数字都是两个,全数字异或的时候就抵消掉了,最后的异或结果其实就是两个不同数字的异或结果。
res = 010
第二步:确定标志位

#第二步:确定标志
        splitBit = 1
        while splitBit & res == 0:
            splitBit = splitBit << 1

该标志的1,可以确定:所求两个数在该位一个为0,一个为1
001&010=000;
splitBit = 010
010&010=010
splitBit = 010
第三步:将数组分为两组,一组在该标志位为1,一组在该标志位为0,并将两组内的数分别异或,得到两个结果则为这两个不同的数
在这里插入图片描述

完整代码

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        res = 0
        #第一步:全数组异或
        for i in array:
            res ^= i
        #第二步:确定标志位
        splitBit = 1
        while splitBit & res == 0:
            splitBit = splitBit << 1
        #第三步
        res1 = 0
        res2 = 0
        for i in array:
            if i & splitBit == 0:
                res1 ^= i
            else:
                res2 ^= i
        return [res1,res2]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值