1.
利用map实现速查,优点是代码简洁,缺点是速度慢,内存大
#include<bits/stdc++.h>
using namespace std;
int a[200005]={0};
int main()
{
int n,c;
scanf("%d%d",&n,&c);
map<int,int> maps;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
maps[a[i]]++;
}
long long ans=0;
for(int i=1;i<=n;i++)
{
ans+=maps[a[i]+c];
}
printf("%lld\n",ans);
return 0;
}
2.
遍历数组,二分查找,总时间复杂度为O(nlogn)
#include<bits/stdc++.h>
using namespace std;
int a[200005]={0};
int main()
{
int n,c;
scanf("%d%d",&n,&c);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
long long ans=0;
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
{
int x=a[i]+c;
int l=i,r=n+1;
while(l<r-1)
{
int mid=(l+r)/2;
if(a[mid]>=x)r=mid;
else l=mid;
}
int left=r;
l=i,r=n+1;
while(l<r-1)
{
int mid=(l+r)/2;
if(a[mid]<=x)l=mid;
else r=mid;
}
int right=l;
ans+=right-left+1;
//printf("%d %d : %d\n",left,right,ans);
}
printf("%lld\n",ans);
return 0;
}
3.
双指针法,时间复杂度O(n),常数项为4
标签:d%,P1102,int,复杂度,数对,scanf,解法,200005
From: https://www.cnblogs.com/pure4knowledge/p/17857434.html