一、数学法思路:题中说其他元素均出现三次。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return (3 * sum(list(set(nums))) - sum(nums)) // 2
二、思路:遍历nums,用字典记录每个元素的次数,遍历字典返回value为1对应的key。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
mydict = {}
for item in nums:
if item in mydict.keys():
mydict[item] += 1
else:
mydict[item] = 1
for k, v in mydict.items():
if v == 1:
return k
三、先转set去重,然后遍历set返回在原list中只出现一次的元素。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
newlist = list(set(nums))
for item in newlist:
if nums.count(item) > 1:
continue
else:
return item