---
# System prepended metadata

title: '**Leetcode筆記(Contains Duplicate)**'
tags: [easy, arrays, leetcode]

---

# **Leetcode筆記(Contains Duplicate)**


:::info
:information_source: 題目 : Contains Duplicate, 類型 : arrays , 等級 : easy
日期 : 2023/02/17，2023/05/03，2023/06/26，2024/10/04
:::


### 嘗試

記憶體好像有點差

```python
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        record = {}
        for i, val in enumerate(nums): 
            if val in record:
                return True  
            record[val] = i
        return False
```
2023/05/03
```python
# 其實是看了優化後才用set

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

        for n in nums:
            if n in record:
                return True
            record.add(n)
        return False
```
2023/06/26
如果有要記錄重複，那就用set
```python
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        record = set()
        for c in nums:
            if c in record:
                return True
            record.add(c)
        return False
```

---
### **優化**

建立set來解，時間複雜度O(n)，空間複雜度O(n)
如果用sort來解這題(把list依大小先排好)，時間複雜度O(nlogn)，空間複雜度O(1)，因為不用用到多餘空間

```python
class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        record = set()
        for i, val in enumerate(nums): 
            if val in record:
                return True  
            record.add(val)
        return False
```
---


**:warning: 錯誤語法** 
:::warning
:::


**:thumbsup:學習** 
:::success
set集合不會包含重複的資料
不用用到index
記得可以if val in set:
![](https://i.imgur.com/PyNP0XO.png)

:::

**思路**
![](https://i.imgur.com/kDPt0Gz.png)


**講解連結**
https://www.youtube.com/watch?v=3OamzN90kPg
Provided by. NeetCode

###### tags: `arrays` `easy` `leetcode`