LeetCode217 Contains Duplicate


描述

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

样例

1
2
Input: 1 2 2 3
Output: true

思路

判断数组中是否有重复的数字。

map记录下即可。

代码

1
2
3
4
5
6
7
8
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> hs;
for (int& x: nums) if (++hs[x] >= 2) return true;
return false;
}
};