2023-11-28|閱讀時間 ‧ 約 3 分鐘

[Leetcode] 217. Contains Duplicate

題目: 217. Contains Duplicate

  • Given an integer array 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


  1. Hashmap
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


  1. sort()

先做排序,將數值依照順序做排序

如果目前的和後一個數值一樣就回傳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








分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.