題目
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Input: [2,2,1]
Output: 1
分析
題目是找出列表中只出現(xiàn)一次的數(shù)。其他數(shù)均出現(xiàn)兩次。
初始話一個字典用來儲存出現(xiàn)次數(shù)。最后找到dic.value為1的`dic.key.
代碼values
class Solution:
def singleNumber(self, nums: List[int]) -> int:
dic={e:2 for e in nums}
for e in nums:
dic[e] -= 1
return list(dic.keys())[list(dic.values()).index(1)]
list(dic.keys())和list(dic.values())分別返回key 和 value的列表