给定一个整数数组nums,如果任一值在数组中出现至少两次,返回true
;如果数组中每个元素互不相同,返回false
方法1: set去重,判断列表去重之后的长度是否和原数组nums的长度相等
def containsDuplicate(nums):
if len(nums) != len(set(nums)):
return True
else:
return False
containsDuplicate([1,2,3,1]) # True
containsDuplicate([1,2,3,4]) # False
containsDuplicate([1,1,1,3,3,4,3,2,4,2]) # True
方法2: 通过排序,然后判断相邻的两个元素是否相等
def containsDuplicate(nums):
nums.sort()
for i in range(len(nums) - 1):
if nums[i + 1] == nums[i]:
return True
return False
containsDuplicate([1,2,3,1]) # True
containsDuplicate([1,2,3,4]) # False
containsDuplicate([1,1,1,3,3,4,3,2,4,2]) # True
方法3
def containsDuplicate(nums):
if len(nums) <= 1:
return False
hashset = set()
for i in nums:
if i in hashset:
return True
else:
hashset.add(i)
return False
containsDuplicate([1,2,3,1]) # True
containsDuplicate([1,2,3,4]) # False
containsDuplicate([1,1,1,3,3,4,3,2,4,2]) # True