首页 > 代码库 > [LeetCode] Contains Duplicate

[LeetCode] 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.

判断数组中是否有重复的数字,如果有返回true,如果没有返回false。利用map求解。

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        unordered_map<int, int> m;
        for (int num : nums)
            m[num]++;
        for (auto it = m.begin(); it != m.end(); it++)
            if (it->second >= 2)
                return true;
        return false;
    }
};
// 39 ms

 

[LeetCode] Contains Duplicate