136.137. 只出現一次的數字 I. II(簡單,中等,陣列)
阿新 • • 發佈:2018-12-16
136.給定一個非空整數陣列,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素。
示例 1:
輸入: [2,2,1] 輸出: 1
方法一:
class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() for i in range(1,len(nums)-1,2): if nums[i-1]!=nums[i]: return nums[i-1] return nums[-1]
方法二:
def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ s={} for i in nums: if i not in s.keys(): s[i]=1 else: s.pop(i) return list(s.keys())[0] #執行用時: 60 ms, 在Single Number的Python3提交中擊敗了54.92% 的使用者
方法三:大神的方法,運用異或的原理
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for i in nums:
res^=i
return res
137.給定一個非空整數陣列,除了某個元素只出現一次以外,其餘每個元素均出現了三次。找出那個只出現了一次的元素。
示例 1:
輸入: [2,2,3,2] 輸出: 3
思路一:最簡單的想法,一個一個的去數,看看哪個數字不是三,但是執行很慢
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in nums:
if nums.count(i)!=3:
return i
執行用時: 1780 ms, 在Single Number II的Python3提交中擊敗了5.84% 的使用者
思路二:每隔三個檢驗一次,看是否相同。檢驗的是每組的前兩個。最後會把最後一個落下,如果迴圈結束的話,就是最後一個數字了。
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
for i in range(1,len(nums)-1,3):
if nums[i-1]!=nums[i]:
return nums[i-1]
return nums[-1]
執行用時: 48 ms, 在Single Number II的Python3提交中擊敗了92.69% 的使用者