Leetcode 刷题 - 260 - Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?


很有意思的bit manipulation的题目。
&,位与运算,能确定两个数字的所有二进制下1的位置。
|, 位或运算,能确定两个数字的所有二进制下0的位置。
^,异或运算,能确定两个数字的所有二进制下不同value的位置。

解题思路:
1. 对list进行异或处理,得到的结果应该就是唯二的两个出现了一次的数字的异或的值。
2. 对于得到的值,value是1的位置,就是两个数字value不同的位置。
for num in nums:
    xor ^= num # 得到两个数字的异或结果

3. 新建一个mask,mask=1,把1的位置移到右起第一个异或结果数值是1的位置。
mask = 1
while mask & xor == 0:
    mask <<= 1 # 循环得到第一个异或结果为1的位置

4. 然后循环list,每一个数字都和mask进行于&运算。
5. 位置是1的是一个group,位置是0的是一个group。当然的,需要的两个结果会在不同的group里面,因为那个位置是异或为1的位置。
6. 然后每个num再和0进行异或运算,重复的出现两次的值会归0.剩下的就是我们需要的结果。
for num in nums: 
    if num & mask: # group 1
        a ^= num
    else:          # group 0
        b ^= num




class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        xor = 0
        a, b = 0, 0
        
        for num in nums:
            xor ^= num
            
        mask = 1
        while mask & xor == 0:
            mask <<= 1
        
        for num in nums:
            if num & mask:
                a ^= num
            else:
                b ^= num
        return [a, b]




===================

二进制 -》 十进制
int('10100111110',2) # 1342

二进制 -》 十六进制
hex(int('101010',2)) # 0x2a

八进制 -》 二进制
bin(int('17',8)) # 0b1111

十进制 -》 二进制
bin(10) # 0b1010




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值