leetcode 260. Single Number III

本题的思路是寻找一组数种出现一次的两个数,此题有如下特点:

1.数异或自己等于0

2.两个不一样的数异或不为0

具体思路看代码

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?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        #1.将所有数异或,找到不为0的值xor
        xor = 0
        for num in nums:
            xor ^= num
        flag = 1
        #2.找到第一个不为1的那一位对应的数flag
        while flag&xor == 0:
            flag = flag << 1 
        #3.将数据分别和flag想与,为1的一组,为0的一组
        rtn1 = 0
        rtn2 = 0
        for num in nums:
            if num & flag !=0 :
                rtn1 ^= num
            else:
                rtn2 ^= num
        return [rtn1,rtn2]

Iyon童鞋的改进

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        #1.将所有数异或,找到不为0的值xor
        xor = 0
        for num in nums:
            xor ^= num
        #2.找到第一个不为1的那一位对应的数flag
        flag = (xor& (xor-1)) ^xor #括号里将第一个为1的位置零,再异或就找到了
        #3.将数据分别和flag想与,为1的一组,为0的一组
        rtn1 = 0
        rtn2 = 0
        for num in nums:
            if num & flag !=0 :
                rtn1 ^= num
            else:
                rtn2 ^= num
        return [rtn1,rtn2]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值