标签:
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.
有两种思路:
排序方法:
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; } };
【LeetCode】217. Contains Duplicate
标签:
原文地址:http://www.cnblogs.com/jdneo/p/4744529.html