[leetcode] Contains Duplicate

时间:2021-09-15 23:33:12

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.

Have you met this question in a real interview?
思路:
1,哈希法:用一个set记录所有出现过的数字,若有冲突,则含有重复元素;若没有冲突,则不含有重复元素。此方法时间复杂度为O(n),空间复杂度为O(n)
 class Solution
{
public:
bool containsDuplicate(vector<int> &nums)
{
set<int> S;
for(int i=; i<nums.size(); i++)
{
if(S.find(nums[i]) == S.end())
S.insert(nums[i]);
else
return true;
}
return false;
}
};
2,排序法:先将该数组排序,然后从i=1开始,num[i-1]与nun[i]两两比较, 若存在相等的情况,则含有重复元素,否则不含有重复元素,此方法时间复杂度为O(nlogn), 空间复杂度为O(1)。
 class Solution
{
public:
bool containsDuplicate(vector<int> &nums)
{
sort(nums.begin(), nums.end());
for(int i=; i<nums.size(); i++)
if(nums[i-] == nums[i])
return true; return false;
}
};