LeetCode----Single NumberIII

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

你可能感兴趣的:(位运算,LeetCode,python,面试题)