---
# System prepended metadata

title: 217. Contains Duplicate
tags: [Leetcode, python, c++, hash, easy]

---

###### tags: `Leetcode` `easy` `hash` `python` `c++`

# 217. Contains Duplicate

## [題目連結:] https://leetcode.com/problems/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
```

## 解題想法:
兄弟題目: [219. Contains Duplicate II](/c-DXz4S2TGyWZ56AcDrndQ)
用個hash table or set紀錄即可，當數字出現過return True

## Python:
``` python=
class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        dic=set()
        for val in nums:
            if val in dic:
                return True
            dic.add(val)
        return False
        '''
        tmp = {}
        for i in nums:
            tmp[i] = tmp.get(i,0)+1
            if tmp[i] >1:
                return True
        return False
        '''
if __name__ == '__main__':
    result = Solution()
    nums = [1,1,1,3,3,4,3,2,4,2]
    ans = result.containsDuplicate(nums)
    print(ans)
```
## C++:
``` cpp=
#include<iostream>
#include<set>
#include<vector>
using namespace std;

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        set<int> dic;
        for (int val:nums){
            if (dic.find(val)!=dic.end())
                return true;
            dic.insert(val);
        }
        return false;
    }
};

int main(){
    vector<int> nums={1,2,3,1};
    Solution res;
    bool ans=res.containsDuplicate(nums);
    cout<<ans<<endl;
    return 0;
}
```