AcWing 3202. 相邻数对
原题链接
简单
作者:
Daylightap
,
2025-03-26 15:33:10
·湖北
,
所有人可见
,
阅读 2
提供O(n^2)写法,O(n logn)写法,O(n)写法
O(n^2)写法
using namespace std;
const int N=1010;
int n;
int q[N];
int main()
{
cin>>n;
for(int i=0;i<n;i++) cin>>q[i];
int res=0;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
if(abs(q[i]-q[j])==1&&i<j)
res++;
}
cout<<res<<endl;
return 0;
}
O(nlogn)写法
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1010;
int n;
int a[N];
bool st[10010];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
sort(a, a + n);
int res = 0;
for (int i = 0; i + 1 < n; i ++ )
if (a[i + 1] - a[i] == 1)
res ++;
printf("%d", res);
return 0;
}
O(n)写法
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1010;
int n;
int a[N];
bool st[10010];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i ++ )
{
int x;
scanf("%d", &x);
a[i] = x;
st[x] = true;
}
int res = 0;
for (int i = 0; i < n; i ++ )
{
int x = a[i], y = x + 1;
if(st[y]) res++;
}
printf("%d", res);
return 0;
}