LeetCode 260. Single Number III

依然还是用熟悉的python写的

问题描述:

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?
很有意思的一道题,因为之前写过single number I,所以这次看到这道题就进来了,刚开始的思路肯定是任意两个相同数的亦或为0,但是这道题有两个single number,假设为a、b,遍历亦或的结果是a^b,没法分别a、b。想了挺久还是没什么思路,后来想过用hash来做,取一个很大很大的hash值x,保证任意数hash x都是它自己,最后取只有一个的hash桶,但这样做的空间复杂度太高。没办法,只能去偷窥答案,发现是实在机智:思路依然是任意两个相同数的亦或为0,那么现在的任务就是把nums分成两段,其中每一段只含有一个single number。how?假设d=a^b,因为a、b是两个不同的值所以d的二进制表示至少有一位是1,同时,a、b在该位上分别为0和1,那么好了,以此作为分别标志,将nums分成两段,分别循环亦或,最后得到的值就是两个singlenumber
代码:
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        d = 0
        for i in nums:
            d ^= i
        d &= -d  #找到最低非1位,负数以补码形式存储
        
        r = [0,0]
        for i in nums:
            if (d&i)==0:
                r[0] ^= i
            else:
                r[1] ^= i
        
        return r
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值