nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
dict_nums = {}
for num in nums:
if num in dict_nums:
return True
dict_nums[num] = dict_nums.get(num,0)+1
return False
先做排序,將數值依照順序做排序
如果目前的和後一個數值一樣就回傳True
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False