---
# System prepended metadata

title: "[LeetCode] 217.\_Contains Duplicate"
tags: [LeetCode]

---

[LeetCode] 217. Contains Duplicate
===
###### tags: `LeetCode`

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

```

**Constraints:**

- `1 <= nums.length <= 105`
- `109 <= nums[i] <= 109`


### 第一版
透過 Set 來儲存已判斷過的值

```=Java
class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        val saveSet = mutableSetOf<Int>()
        for (i in 0 until nums.size) {
            if (!saveSet.add(nums[i])) {// 加入失敗，表示已經存過了，此數值出現了第二次，回傳 true
                return true
            }
        }
        return false
    }
}
```
**Success**

[Details](https://leetcode.com/submissions/detail/621581480/)

Runtime: 751 ms, faster than 22.41% of Kotlin online submissions for Contains Duplicate.

Memory Usage: 72.2 MB, less than 15.75% of Kotlin online submissions for Contains Duplicate.

---

### 第二版
直接將 array 轉成 set

```=Java
class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        val set = nums.toSet()
        if (nums.size == set.size) {
            return false
        }
        return true
    }
}
```
**Success**

[Details](https://leetcode.com/submissions/detail/621580649/)

Runtime: 428 ms, faster than 49.04% of Kotlin online submissions for Contains Duplicate.

Memory Usage: 50.7 MB, less than 54.03% of Kotlin online submissions for Contains Duplicate.


---

### 第三版
Solution 1 換一種 for loop

```=Java
class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        val saveSet = mutableSetOf<Int>()
        for (num in nums) {
            if (!saveSet.add(num)) {
                return true
            }
        }
        return false
    }
}
```
**Success**

[Details](https://leetcode.com/submissions/detail/621585885/)

Runtime: 368 ms, faster than 66.97% of Kotlin online submissions for Contains Duplicate.

Memory Usage: 45.2 MB, less than 75.16% of Kotlin online submissions for Contains Duplicate.


---

### 最終版
mutableSetOf 改成 HashSet

```=Java
class Solution {
    fun containsDuplicate(nums: IntArray): Boolean {
        val saveSet = HashSet<Int>()
        for (num in nums) {
            if (!saveSet.add(num)) {
                return true
            }
        }
        return false
    }
}
```

**Success**

[Details](https://leetcode.com/submissions/detail/621586620/)

Runtime: 336 ms, faster than 75.80% of Kotlin online submissions for Contains Duplicate.

Memory Usage: 45.1 MB, less than 75.16% of Kotlin online submissions for Contains Duplicate.