LeetCode--136--只出現一次的數字
阿新 • • 發佈:2018-09-12
實現 額外 比較 pre 整數 etc -- tco tro
問題描述:
給定一個非空整數數組,除了某個元素只出現一次以外,其余每個元素均出現兩次。找出那個只出現了一次的元素。
說明:
你的算法應該具有線性時間復雜度。 你可以不使用額外空間來實現嗎?
示例 1:
輸入: [2,2,1] 輸出: 1
示例 2:
輸入: [4,1,2,1,2] 輸出: 4
方法1:1 ^ 1 = 0 ,1 ^ 0 = 1
1 class Solution(object): 2 def singleNumber(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int6 """ 7 for i in range(1,len(nums)): 8 nums[0] ^= nums[i] 9 return nums[0]
方法2:字典法
1 def singleNumber(self, nums): 2 """ 3 :type nums: List[int] 4 :rtype: int 5 """ 6 res = {} 7 for i in nums: 8 ifi in res: 9 res.pop(i) 10 else: 11 res[i]=1 12 return list(res.keys())[0]
方法3:排序後比較大小
1 class Solution(object): 2 def singleNumber(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 nums.sort()8 for i in range(1,len(nums),2): 9 if(nums[i]>nums[i-1]): 10 return nums[i-1] 11 return nums[len(nums)-1]
2018-09-12 20:32:15
LeetCode--136--只出現一次的數字