[Python]陣列中只出現一次的數字
阿新 • • 發佈:2018-12-26
題目描述:
一個整型數組裡除了兩個數字之外,其他的數字都出現了兩次。請寫程式找出這兩個只出現一次的數字。
解法1:
通過遍歷把統計的數字次數存入python內建的字典dict,然後再搜尋出現一次的數字
class Solution:
# 返回[a,b] 其中ab是出現一次的兩個數字
def FindNumsAppearOnce(self, array):
# write code here
tagdict={}
for i in array:
if i in tagdict:
tagdict[i]+=1
else:
tagdict[i]=1
taglist=[]
for j in tagdict:
if tagdict[j]==1:
taglist.append(j)
return taglist
解法2:
通過使用python的count計數函式
class Solution:
# 返回[a,b] 其中ab是出現一次的兩個數字
def FindNumsAppearOnce(self, array):
# write code here
taglist=[]
for i in array:
if array.count(i)==1 and i not in taglist:
taglist.append(i)
return taglist
兩種方法在牛客網提交的測評結果對比
法1:執行時間:24 ms 佔用記憶體:5624K
法2:執行時間:32 ms 佔用記憶體:5628K