给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
思路一:建立哈希映射:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int,int>hash;
for(int x:nums){
hash[x]++;
}
unordered_map<int,int>::iterator it=hash.begin();
while(it!=hash.end()){
if(it->second>1){
return true;
}
it++;
}
return false;
}
};
思路二:先排序,再比较相邻元素
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(),nums.end());
int index=1;
int len=nums.size();
if(len==0)
return false;
while(index<len){
if(nums[index]==nums[index-1])
return true;
index++;
}
return false;
}
};