美文网首页
数组中只出现一次的数字

数组中只出现一次的数字

作者: Haward_ | 来源:发表于2019-04-21 17:40 被阅读0次

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

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出现一次的两个数字
    def FindNumsAppearOnce(self, array):
        # write code here
        t = 0
        for a in array:
            t ^= a
        nBit = self.findNbit(t)
        t1,t2 = 0,0
        for a in array:
            if self.findNbitIsOne(a,nBit):
                t1 ^= a
            else:
                t2 ^= a
        return [t1,t2]
                
    def findNbit(self,n):
        res = 0
        t = 1
        while n & t == 0:
            res += 1
            t <<= 1
        return res
    
    def findNbitIsOne(self,n,nBit):
        t = 1
        t <<= nBit
        return n & t > 0

相关文章

网友评论

      本文标题:数组中只出现一次的数字

      本文链接:https://www.haomeiwen.com/subject/pkpjgqtx.html