Contains Duplicate
1、题目:
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.
2、代码:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if(nums.size()<=1)
{
return false;
}
sort(nums.begin(),nums.end());
for(auto iter=nums.begin()+1;iter!=nums.end();++iter)
{
if(*iter==*(iter-1))
{
return true;
}
}
return false;
}
};
3、总结:
不涉及索引,所以不用pair,但是排序过后肯定是很好判断的。
Contains Duplicate II
1、题目:
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
2、代码:
class Solution {
public:
static bool compare(pair<int,int> &pa,pair<int,int> &pb)
{
return pa.first<pb.first;
}
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.empty()) return false;
vector<pair<int,int>> vp;
int i=0;
for(const int &im:nums)
{
vp.push_back({im,i++});
}
sort(vp.begin(),vp.end(),compare);//stable_sort更好
for(auto iter=vp.begin();iter!=vp.end();++iter)
{
for(auto iter1=iter+1;iter1!=vp.end()&&iter->first==iter1->first;++iter,++iter1)
{
if(iter1->second-iter->second<=k)
{
return true;
}
}
}
return false;
}
};
3、总结:
只要相等就检查索引,不合要求两个迭代器都前进,因为两个相邻的索引差最小。
Contains Duplicate III
1、题目:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
2、代码:
class Solution {
public:
static bool compare(pair<int,int> &pa,pair<int,int> &pb)
{
return pa.first<pb.first;
}
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(nums.empty()) return false;//k索引,t差值
vector<pair<int,int>> vp;
int i=0;
for(const int &im:nums)
{
vp.push_back({im,i++});
}
sort(vp.begin(),vp.end(),compare);//stable_sort
for(auto iter=vp.begin();iter!=vp.end();++iter)
{
for(auto iter1=iter+1;iter1!=vp.end();)
{
if(iter1->first<=t+iter->first)//防止溢出
{
//abs()防止索引变负
if(abs(iter1->second-iter->second)<=k)
{
return true;
}
else
{
++iter1;
}
}
else
{
break;
}
}
}
return false;
}
};
3、总结:
A、if(iter1->first<=t+iter->first)//防止溢出,这里本来不是这么写的,原来是iter1->first-iter->first<=t,后来发现当大的比较大,小的为负时候,会溢出。其实这么改也不是最好的,我是根据case改的,如果会溢出的话显然升级整型最好。
B、 if(abs(iter1->second-iter->second)<=k)//abs()防止索引变负
当两个数差值符合要求时候,有可能索引差值为负。
C、stable_sort()与sort()。无法知晓,leetcode好像不支持stable_sort()。但是发现sort()效果在这里好像是一样的。以上推断仅就leetcode而言。