题目链接
https://leetcode-cn.com/problems/single-number/
题目描述
代码欣赏
方法1:哈希表
- 思路:用哈希表表存储数字以及对应的个数
- 实现:
1.遍历nums 中的每一个元素
2.查找hash_table 中是否有当前元素的键
3.如果没有,将当前元素作为键插入hash_table
4.最后, hash_table 中仅有一个元素,用 popitem 获得它
class Solution:
def singleNumber(self, nums: List[int]) -> int:
hash_table={}
for i in nums:
try:
hash_table.pop(i)
except:
hash_table[i]=1
#popitem()可以随机pop一个turple出来,而pop必须指定key
return hash_table.popitem()[0]
时间复杂度: O(n *1) = O(n)O(n⋅1)=O(n)
空间复杂度: O(n),hash_table 需要的空间与 nums 中元素个数相等
方法2:列表操作
- 思路:列表中保存新出现的数字,再出现就一起remove掉,一山不容二虎。
- 实现:
1.遍历nums 中的每一个元素
2.如果某个 nums 中的数字是新出现的,则将它添加到列表中
3.如果某个数字已经在列表中,删除它
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
no_duplicate_list = []
for i in nums:
if i not in no_duplicate_list:
no_duplicate_list.append(i)
else:
no_duplicate_list.remove(i)
return no_duplicate_list.pop()