题目:
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.
提示:
有两种思路:
- 对输入的数组进行排序,然后比较相邻元素的值是否一致 - O(nlgn);
- 利用Hash Set - O(n)。
代码:
排序方法:
class Solution { public: bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); return unique(nums.begin(), nums.end()) != nums.end(); } };
利用Hash Set:
class Solution { public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> unset; for (int i = 0; i < nums.size(); ++i) { if (unset.find(nums[i]) != unset.end()) return true; else unset.insert(nums[i]); } return false; } };