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. Sort the array and then compare
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
vector<int> array=nums;
std::sort(array.begin(),array.end());
for(int i=1;i<array.size();i++)
{
if(array[i]==array[i-1])
return true;
}
return false;
}
};
2. Use unordered_set with Time complexity O(n) and space complexity O(n)
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> aset;
for(auto i : nums)
{
if(aset.find(i)!=aset.end())
return true;
aset.insert(i);
}
return false;
}
};
Another highly mathematical solution:
http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/
The difference between map, hash_map, unordered_map and unordered_set:
http://blog.youkuaiyun.com/u013195320/article/details/23046305