[Leetcode] 217. Contains Duplicate

閱讀時間約 2 分鐘

題目: 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








7會員
47內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
Youna's Devlog 的其他內容
[Leetcode] 242. Valid Anagram
閱讀時間約 3 分鐘
你可能也想看
[LeetCode] 875 - Koko Eating Bananas[LeetCode] 875 - Koko Eating Bananas 解題
avatar
Tumi
2024-02-29
Leetcode 30 天 Pandas 挑戰分享參加Leetcode的30 Days of Pandas挑戰,除了是學習的機會,更是練習熟悉pandas功能的機會。文章分享了挑戰簡介、題目描述、關鍵技術以及參加挑戰的心得。適合新手學習pandas,也可提升熟練度。
Thumbnail
avatar
Karen
2024-01-30
LeetCode | 20 Valid Parentheses / 堆疊 (Stack)從 leetcode 學資料結構堆疊 (stack)
Thumbnail
avatar
Jeremy Ho
2023-12-03
LeetCode | 518 Coin Change IILeetCode 518. Coin Challenge II / 動態規劃
Thumbnail
avatar
Jeremy Ho
2023-08-11
LeetCode:刷題網站的陷阱?學習演算法還有更好的方法! Write with chatgptLeetCode是一個學習演算法的網站,而非評斷技術能力的工具。本文將探討LeetCode對工程師的幫助、在面試中的地位、問題與限制,以及演算法是否是工程師必要的技能。此外,我們還提供有效學習演算法的建議。
Thumbnail
avatar
j172tw Blogz
2023-05-29
【LeetCode】946. Validate Stack Sequences 題目 Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop
Thumbnail
avatar
2023-04-15
LeetCode - Rings and Rods #2103 Easy刷題筆記 Easy 題目說明:總共有 10 根竿子,3 種顏色,給予一 string 名為 rings,Ex: R0G1B2 意思是 第1根( index = 0 )有一個紅戒子,第2根( index = 1)有一個綠戒子,第3根(index = 2)有一個藍戒子 目標:回傳有幾根竿子同時有三個顏
avatar
Eason
2023-01-08
【LeetCode】896. Monotonic Array || 這一刻,意識到了自己的成長。題目: 給一個陣列,判斷內容是不是遞增或遞減
Thumbnail
avatar
2022-04-22
【LeetCode】19.Remove Nth Node From End of ListInput: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Thumbnail
avatar
2021-10-09
【LeetCode】876. Middle of the Linked ListInput: head = [1,2,3,4,5] Output: [3,4,5] 單看列表只是要找中間值,不過給定的資料結構不是陣列,而是鏈結串列。
Thumbnail
avatar
2021-10-09