[LeetCode][Python]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?

思路:很久没解题了,发现一点思路也没有了。

一,python的set是一个无序不重复元素集,基本功能包括关系测试和消除重复元素. 集合对象还支持并、交、差、对称差等。所以这里可以使用set的这个功能。使用两个set分别放nums立面的数据,一个set里面已经有的,就放入另外一个,二者差值就是我们要求的。

二, 使用亦或,如果对所有nums里面的数都使用异或,最后的结果就是我们要求的数异或的结果,因为其他重复的值异或的结果变成0了。然后查看这两个数异或的结果,如果一些字节异或的结果为1,则表明这两个数在那个位置不同。

然后把所有数字分成两组,一组是在对应位置为1的,另一组在对应位置不为1。两个不同的数字就是我们要找的。

技巧: diff &= -diff

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        one = set()
        double = set()
        for n in nums:
            if n not in one:
                one.add(n)
            else:
                double.add(n)
        print one
        print double
        return list(one - double)

    def singleNumber2(self, nums):
        diff = 0
        for n in nums:
            diff ^= n
        #Get its last set bit
        diff &= -diff

        res = [0, 0]
        for n in nums:
            if(n&diff==0):
                res[0] ^= n
            else:
                res[1]^=n

        return res

if __name__ == '__main__':
    sol = Solution()
    nums = [1, 2, 1, 3, 2, 5]
    print sol.singleNumber(nums)
    print sol.singleNumber2(nums)

你可能感兴趣的:([LeetCode][Python]260. Single Number III)