使用哈希表(字典),出现访问错误会报KeyError,若未出现即返回True,否则返回False,复杂度O(N)
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
visited = {}
for num in nums:
try:
temp = visited[num]
return True
except KeyError:
visited[num] = 'h'
return False
或者:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
visited = {}
for num in nums:
if num in visited:
return True
else:
visited[num] = 'h'
return False
或使用set:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums))