爽歪歪666
不以物喜,不以己悲,努力才是永恒的主题。

题目描述

一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路
相同异或为0,相异异或为0,有两个出现一次,其他出现两次,想办法将这两个只出现一次的两个数分到不同的数组中。因为两个只出现1个,所以总体异或必不为0,从右往左,找第一个1的索引。根据这个索引把这个索引上是1的归为一组,其他的归为一组。
代码实现
 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def FindNumsAppearOnce(self, array):
 4         # write code here
 5         if not array or len(array) < 2:
 6             return 0
 7         temp = 0
 8         res1 = 0
 9         res2 = 0
10         for i in array:
11             temp = temp ^ i
12         # temp中1在的索引
13         indexof1 = self.findIndex1(temp)
14         for j in array:
15             if self.is1(j,indexof1):
16                 res1=res1^j
17             else:
18                 res2 = res2^j
19         return res1,res2
20 
21     def findIndex1(self,num):
22       23         n = 0
24         while num &1==0:
25             num = num>>1
26             n +=1
27         return n
28     def is1(self,num,index1):
29         if (num>>index1)&1:
30             return True
31         else:
32             return False

 

posted on 2020-04-25 16:29  爽歪歪666  阅读(193)  评论(0编辑  收藏  举报