1. 程式人生 > >LeetCode136:Single Number

LeetCode136:Single Number

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

LeetCode:連結

LeetCode變體:LeetCode137:Single Number II

LeetCode260:Single Number III

劍指Offer_程式設計題40:陣列中只出現一次的數字(異或)的簡單版。

^ 按位異或運算子:當兩對應的二進位相異時,結果為1

任何一個數字異或它自己都等於0 。也就是說,如果我們從頭到尾依次異或陣列中的每一個數字,那麼最終的結果剛好是那個只出現一次的數字。比如陣列{4,5,5},我們先用陣列中的第一個元素4(二進位制形式:0100)和陣列中的第二個元素5(二進位制形式:0101)進行異或操作,0100和0101異或得到0001,用這個得到的元素與陣列中的三個元素5(二進位制形式:0101)進行異或操作,0001和0101異或得到0100,正好是結果數字4。這是因為陣列中相同的元素異或是為0的,因此就只剩下那個不成對的孤苦伶仃元素。

A和0異或的結果還是A
 

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        remain = 0
        for num in nums:
            remain ^= num
        return remain