1. 程式人生 > >LeetCode260:Single Number III

LeetCode260: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.

Example:

Input:  [1,2,1,3,2,5]
Output: [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?

LeetCode:連結

劍指offer同題:連結劍指Offer_程式設計題40:陣列中只出現一次的數字(異或)

我們還是從頭到尾一次異或陣列中的每一個數字,那麼最終得到的結果就是兩個只出現一次的陣列的異或結果。因為其他數字都出現了兩次,在異或中全部抵消了。由於兩個數字肯定不一樣,那麼異或的結果肯定不為0,也就是說這個結果陣列的二進位制表示至少有一個位為1。我們在結果陣列中找到第一個為1的位的位置,記為第n位

現在我們以第n位是不是1為標準把元陣列中的數字分成兩個子陣列,第一個子陣列中每個數字的第n位都是1,而第二個子陣列中每個數字的第n位都是0。

A和0異或的結果還是A。

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        remain, index = 0, 1
        '''得到A和B異或的結果'''
        for num in nums:
            remain ^= num
        '''根據異或的結果找到從右往左的第一個1'''
        while remain & index == 0:
            index = index << 1
        remain1, remain2 = 0, 0
        '''分組判斷 必須判斷是否為0'''
        for num in nums:
            if num & index == 0:
                remain1 ^= num
            else:
                remain2 ^= num
        return [remain1, remain2]