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








分享至
成為作者繼續創作的動力吧!
這裡會放一些我寫過的 Leetcode 解題,目前的筆記都是使用python做解題
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

Youna's Devlog 的其他內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.