小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
217. 存在重复元素
-
给定一个整数数组,判断是否存在重复元素。
-
如果存在一值在数组中出现至少两次,函数返回
true。如果数组中每个元素都不相同,则返回false。
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
【暴力法】
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int size = nums.size();
for(int i = 0;i<size-1;i++){
for(int j = i+1; j<size;j++){
if(nums[i] == nums[j]){
return true;
}
}
}
return false;
}
};
采用暴力法会超出时间限制
【暴力法改进】
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(),nums.end());
for(int i = 0 ;i<nums.size()-1;i++){
if(nums[i]==nums[i+1]){
return true;
}
}
return false;
}
};
/*
复杂度分析
时间复杂度 : O(n·logn) , 其中n为数组的长度,对数据进行排序
空间复杂度 : O(logn) , 其中n为数组的长度,这里考虑了递归调用栈的深度
*/
【哈希表】
class Solution
{
public:
bool containsDuplicate(vector<int> &nums)
{
// 哈希表
unordered_set<int> s;
for (int num : nums)
{
if (s.find(num) != s.end())
{
return true;
}
s.insert(num);
}
return false;
}
};
/*
复杂度分析
时间复杂度 : O(n) , 其中n为数组的长度,对数据进行排序
空间复杂度 : O(n) , 其中n为数组的长度,这里考虑了递归调用栈的深度
*/
【博文推荐】: