LeetCode----Single NumberIII

95 篇文章 0 订阅
93 篇文章 0 订阅

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?

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


分析:

数组中所有元素均出现过两次,除了两个不相同的元素,设为a和b。当我们将数组中所有元素均进行异或后,能够得到c = a ^ b。那么如何从c解出a和b呢?

事实上,a和b互不相同,则a ^ b的值一定不为0,所以c不为0。设c的第m位为1,那么这个1肯定来自a或者b。我们以此将数组分为两部分,第一部分是该m位含有1的,设为x;另一部分是第m位为0的,设为y。令x中所有元素进行异或,那么得出的值为a或者b中第m位含有1的那个数;同理可得a和b中第m位为0的那个数,从而得到a和b的值。


代码:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        res = 0
        a, b = 0, 0
        for i in nums:
            res ^= i
        # 得出第m位不为0的m值
        for pos in range(0, 32):
            if res & 1 << pos:
                break
        # 得出的值为a或者b中第m位含有1的那个数
        for i in nums:
            if self.isbit(i, pos):
                a ^= i
        # 得a和b中第m位为0的那个数
        for i in nums:
            if not self.isbit(i, pos):
                b ^= i
        return [a, b]

    def isbit(self, n, i):
        return n >> i & 1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值