[LeetCode][Python]260. Single Number III

1929 ワード

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:
  • The order of the result is not important. So in the above example, [5, 3] is also correct.
  • Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

  • 考え方:久しぶりに問題を解いたが、少しも考えがなくなったことに気づいた.
    一、pythonのsetは無秩序な重複要素セットであり、基本機能は関係テストと重複要素の除去を含む.集合オブジェクトは、並列、交差、差、対称差などもサポートします.だからここではsetのこの機能を使うことができます.2つのsetを使ってnums立面のデータをそれぞれ入れて、1つのsetの中にすでにあるので、もう1つを入れて、両者の差は私たちが要求したのです.
    二、使用するか、numsの中のすべての数に対して異或を使用すると、最後の結果は私たちが要求した数異或の結果です.他の重複した値異或の結果は0になったからです.次に、この2つの数の相違の結果を表示します.いくつかのバイトの相違の結果が1の場合、この2つの数はその位置で異なることを示します.
    そしてすべての数字を2つのグループに分けて、1つのグループは対応位置で1で、もう1つのグループは対応位置で1ではありません.2つの異なる数字は私たちが探しているものです.
    テクニック: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)