• 牛客网-数组只出现一次的数字(异或)


    题目描述:

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

    自己提交代码:

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

     提升代码:

    对所有元素进行异或,结果是两个无重复数字的异或和。(相同数字的异或值为0)。因此根据异或结果将这两个数字分开(根据异或结果第一个为1的位数,将此位都为1的放一起,不为1的放一起,然后对这两组进行异或可以分别得到这两个没有重复的数字)。

    class Solution:
        # 返回[a,b] 其中ab是出现一次的两个数字
        def FindNumsAppearOnce(self, array):
            # write code here
            if len(array)==2:
                return array
            temp = 0
            for i in array:
                temp ^= i
            index = self.FindFrist(temp)
            a,b=0,0
            for num in array:
                if self.bitFind(num,index)==1:
                    a ^= num
                else:
                    b ^= num
            return [a,b]
        def FindFrist(self,temp):
            index = 0
            while(temp&1==0 and index<32):
                temp >>= 1
                index += 1
            return index
        def bitFind(self,temp,index):
            temp >>= index
            return 1 if temp&1==1 else 0
    
  • 相关阅读:
    课后作业-阅读任务-阅读提问-4
    团队-象棋游戏-开发文档
    团队-象棋游戏-模块测试过程
    团队编程项目作业3-模块开发过程
    团队-象棋游戏-项目进度
    团队编程总结
    团队编程项目作业,维护
    个人编程总结2
    阅读笔记4
    课后提问4
  • 原文地址:https://www.cnblogs.com/ditingz/p/12146109.html
Copyright © 2020-2023  润新知