存在重复数组
1. 先排序再相邻比较
时间复杂度是 O(NlogN)(N是数组长度)
空间复杂度 O(logN)
bool containsDuplicate(vector<int> nums) {
//先排序 从小到大
int temp,len;
len=nums.size();
sort(nums.begin(),nums.end());
for(int i=0;i<len-1;i++)//相邻两个比较
{
if(nums[i]==nums[i+1])
{
return true;
}
}
return false;
}
2. 利用哈希表解决
时间复杂度是O(N)(N是数组长度)
空间复杂度 O(N)
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
// 构建哈希表
unordered_set<int> un;
for (int x: nums){
// 如果find()找到哈希表中有相等元素,那么返回一个迭代器。true 说明有重复元素
if(un.find(x) != un.end()){
return true; // 有相同元素
}
un.insert(x);
}
return false; // 无重复元素
}
};