1. 程式人生 > >leetcode 136 Single Number(只出現一次的數字) python3 多種思路(建立字典/排序/巧用異或)

leetcode 136 Single Number(只出現一次的數字) python3 多種思路(建立字典/排序/巧用異或)

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        # 思路一:  這種簡單的遍歷太笨拙了 TLE
        # for i in nums:
        #     n  = nums.count(i)
        #     if n ==1:
        #         return i

        # 思路二: 用python 內建的Counter 函式搞事情 例如:numss = [2,2,1,1,1,3]   得到  {1: 3, 2: 2, 3: 1} . 可以減少遍歷的次數
# from collections import Counter # dict_nums = dict(Counter(nums)) # nums_list = dict_nums.keys() # for i in nums_list: # if dict_nums[i]==1: # return i # 思路三: list排序 # 容易想到的思路,對於所有數字排序,只需比較相鄰兩個是否相同,步長為二.缺點是排序耗費時間 # 為了解決可能存在的越界問題,需要在排序後的陣列中新增一個元素.
# new = sorted(nums) # new.append(-0.1) # for i in range(0,len(new),2): # if new[i] != new[i+1]: # return new[i] # 思路四: 元素異或操作 # 異或的自反性:對於某個數E ,用相同的運算因子做兩次異或操作,最後的結果還是 E 本身. 一下是舉例說明: # 由於A XOR A = 0 且 ((A^A) ^ (B^B) ^ (C^C) ^ (D^D) ^ E) = ((0^ 0 ^ 0 ^ 0 ^ E) =E
# 直接把整個陣列異或運算,最後的出來的就是隻出現一次的數字了。 # 這個性質常應用在加密,資料傳輸,校驗等領域. result = 0 for x in nums: result ^= x return result # 思路拓展,舉一反三! # 找出只出現了一次的N個數字 https://www.lijinma.com/blog/2014/05/29/amazing-xor/ # 在出現在N(2,4.....)次的一堆數字中找出只出現一次的那個數字 http://blademastercoder.github.io/2015/01/27/leetcode-findnum.html