給定一個整數(shù)數(shù)組,判斷是否存在重復元素。
如果任何值在數(shù)組中出現(xiàn)至少兩次,函數(shù)返回 true。如果數(shù)組中每個元素都不相同,則返回 false。
示例 1:
輸入: [1,2,3,1]
輸出: true
示例 2:
輸入: [1,2,3,4]
輸出: false
示例 3:
輸入: [1,1,1,3,3,4,3,2,4,2]
輸出: true
- show the code:
### code1
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dic = {}
for num in nums:
if num not in dic:
dic[num] = 1
else:
return True
return False
### code2
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(set(nums)) != len(nums)
- 此題屬于簡單題,代碼一使用hash法,代碼二使用python特有的集合
set法。