【LEETCODE】260-Single Number III

1630 ワード

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?
タイトル:
2つの要素が1回しか現れず、残りの要素が2回現れ、この2つの要素が見つかります.
注意:
結果の要素の順序を維持する必要はありません
アルゴリズムは線形時間の複雑さであり、余分な空間は必要ありません.
考え方:
1.dictを確立し、出現回数を統計し、復帰回数==1の要素
2.ビット操作:
http://bookshadow.com/weblog/2015/08/17/leetcode-single-number-iii/
方法1:
class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        
        A={}
        B=[]
        
        for i in nums:
            if i not in A:
                A[i]=1
            else:
                A[i]=2
        
        for i in A:
            if A[i]==1:
                B.append(i)
        
        return B

方法2:
ああ、知能指数は急いで、理解していません!!
class Solution:
    # @param {integer[]} nums
    # @return {integer[]}
    def singleNumber(self, nums):
        xor = reduce(lambda x, y : x ^ y, nums)
        lowbit = xor & -xor
        a = b = 0
        for num in nums:
            if num & lowbit:
                a ^= num
            else:
                b ^= num
        return [a, b]