0%
Loading ...

【Leetcode 筆記】 217. Contains Duplicate

題目解釋

每個 element 只能出現一次,若出現超過兩次就回傳 True

範例

  • 輸入: nums = [1, 2, 3, 1]
  • 輸出: True

因為 1 出現了兩次所以有 duplicate,回傳 True

最佳解法

只需要判定有沒有出現過,可以用 hash map,但我覺得更適合用 set 還可以少存 value 值。

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        appeared = set()

        for n in nums:
            if n not in appeared:
                appeared.add(n)
            else:
                return True
        return False

時間複雜度

O(n)

空間複雜度

O(n)

結語

面試時可以考我這個嗎 QQ

數據女巫 𝔻.𝕡𝕪𝕤 🔮

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.