总觉得在哪里写过类似的题。。但是想不起来了!
本蠢逼第一时间想到了双重循环,o(n^2)的时间复杂度。。算了
然后看别人的思路,学到了一个新的方法,就是在map中find
auto it2=hash.find(k+it->first);
if(it2!=hash.end()) ans++;
简单的两行代码,就能找到符合要求的key值,妈妈再也不用担心的我时间复杂度
代码
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
//特判
if(k<0) return 0;
map<int,int>hash;
for(int i:nums)
{
hash[i]++;
}
int ans=0;
if(k==0)
{
for(auto it=hash.begin();it!=hash.end();it++)
{
if(it->second>1) ans++;
}
}
else
{
for(auto it=hash.begin();it!=hash.end();it++)
{
//新方法! 在map中find一个值 ..总觉得在LeetCode上写过似曾相识的题目。。
//在这样也能保证 不会出现(i,j)和(j,i)也计入答案的情况
auto it2=hash.find(k+it->first);
if(it2!=hash.end()) ans++;
}
}
return ans;
// //双重循环 太暴力了
// sort(nums.begin(),nums.end());
// map<int,int>match;
// int ans=0;
// for(int i=0;i<nums.size();i++)
// {
// for(int j=i+1;j<nums.size();j++)
// {
// if(abs(nums[i]-nums[j])==k)
// {
// //特殊的hash规则
// if(match[nums[i]]!=nums[j]+367)
// ans++;
// // if(nums[i]>nums[j])
// match[nums[i]]=nums[j]+367;
// cout<<nums[i]<<" "<<nums[j]<<endl;
// }
// }
// }
// return ans;
}
};