问题描述:
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
解释:其中前三种是我写的,后面两种是抄的
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
set_nums = set(nums)
for item in set_nums:
if nums.count(item) == 1:
return item
return -1
def singleNumber1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret_dict = {}
for item in nums:
count = ret_dict.get(item, 0)
if count == 1:
del ret_dict[item]
continue
ret_dict[item] = count + 1
return list(ret_dict.keys())[0]
def singleNumber2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in nums:
if nums.count(i) == 1:
return i
def singleNumber3(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = 0
for i in nums:
ret = ret ^ i
return ret
def singleNumber4(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(set(nums))*2 - sum(nums)
if __name__ == '__main__':
s1 = Solution()
nums = [4, 1, 2, 1, 2]
print(s1.singleNumber4(nums))