问题描述:
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.
//第一种方法
//先将用sort将数组排序,然后通过一次遍历数组,判断有无重复数字,最开始我用
//的连个for去做的,但是当测试样例特别大的时候,会时间超限,时间复杂度为
//O(n*n),用现在这个方法时间复杂度是O(n),不会超限
class Solution {
public:
bool containsDuplicate(vector<int>& nums)
{
sort(nums.begin(),nums.end());//对数组排序
for(int i=1;i<nums.size();i++)
{
if(nums[i]==nums[i-1])//注意数组越界问题
return true;
}
return false;
}
};
//第二种方法
//hash,判断key值是否大于1
class Solution {
public:
bool containsDuplicate(vector<int>& nums)
{
unordered_map<int,int> mp;//时间复杂度为(lgn)
for(int i:nums)//遍历数组
{
mp[i]++;//i对应的value的key+1
// unordered_map内部是哈希表,key—value之间的关系就像人名和人一样,key就是人名,value就是人的对象,一个键值对应一个value
if(mp[i]>1)
return true;
}
return false;
}
};
//第三种
//通过集合比较与原数组的大小
class Solution {
public:
bool containsDuplicate(vector<int>& nums)
{
unordered_set<int> st(nums.begin(),nums.end());
return nums.size()>st.size();
}
};
以上程序注释只是我自己的理解,不一定对,仅供参考