---
tags: LeetCode
disqus: HackMD
---
# Contains Duplicate
# 題目連結
[Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
# 中文
## 直覺
<!-- Describe your first thoughts on how to solve this problem. -->
使用set與原數組長度進行比較
## 方法
<!-- Describe your approach to solving the problem. -->
代碼中的"`new Set(nums)`"創建了一個集合對象,並將陣列`nums`中的所有元素添加到集合中。由於集合中不能包含重複元素,因此如果陣列中有重複元素,則集合的大小將不等於陣列的長度。
代碼中的下一行, '`return new Set(nums).size !== nums.length`' ,則是判斷陣列中有沒有重複元素的關鍵部分。如果集合的大小不等於陣列的長度,則返回true,表示陣列中有重複元素;如果集合的大小等於陣列的長度,則返回false,表示陣列中沒有重複元素。
## 複雜度
- 時間複雜度:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
對於時間複雜度,集合中插入元素的時間複雜度為O(1),因此總時間複雜度為O(n)。
$$O(n)$$
- 空間複雜度:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
對於空間複雜度,創建了一個大小為n的集合,因此空間複雜度為O(n)。
$$O(n)$$
## 程式碼
```javascript=
/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
return new Set(nums).size !== nums.length
};
```
# 英文
## Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Use set to compare with the original array length
## Approach
<!-- Describe your approach to solving the problem. -->
The code creates a set object by "new Set(nums)" and add all elements of the array nums to the set. Because a set can not contain duplicate elements, if there are duplicate elements in the array, the size of the set will not be equal to the length of the array.
The next line of the code, 'return new Set(nums).size !== nums.length', is the key part that checking the duplicate of the array. If the size of the set is not equal to the length of the array, it returns true, indicating that there are duplicate elements in the array; if the size of the set is equal to the length of the array, it returns false, indicating that there are no duplicate elements in the array.
## Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
For time complexity, the time complexity of inserting elements into the set is O(1), so the total time complexity is O(n).
$$O(n)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
For space complexity, a set of size n is created, so the space complexity is O(n).
$$O(n)$$
## Code
```javascript=
/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {
return new Set(nums).size !== nums.length
};
```