LeetCode 217. Contains Duplicate 题解(C++) 题目描述 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. 思路 使用STL的关联容器unordered_map,对数组遍历,把每个元素出现的次数记录map里,若在某次循环过程中,该元素出现的次数等于2,则返回true,否则遍历完成则返回false。 代码 class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_map<int, int> hashMap; for (auto num : nums) { hashMap[num]++; if (hashMap[num] == 2) { return true; } } return false; } };