
一、核心思路
在一个有序数组中,快速查询给定区间 [x, y] 内的元素个数 ,核心实现方式是二分查找。
要统计数组中满足 的元素个数,关键是找到两个边界,同时还需检查边界的合法性。
二、代码实现
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10;
LL a[N];
int n,q;
void solve(LL x, LL y)
{
int l = 1, r = n;
// 1.左边界
while(l < r)
{
LL mid = (l + r) >> 1;
if (a[mid] < x) l = mid + 1;
else r = mid;
}
int retl = l;
// 2.右边界
l = 1, r = n;
while(l < r)
{
int mid = (l + r + 1) >> 1;
if (a[mid] > y) r = mid - 1;
else l = mid;
}
if (a[retl] > y || a[l] < x) cout << 0 << endl;
else cout << l - retl + 1 << endl;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
cin >> q;
while(q--)
{
LL x, y; cin >> x >> y;
solve(x,y);
}
return 0;
}
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10;
LL a[N];
int n,q;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
cin >> q;
while(q--)
{
LL x, y; cin >> x >> y;
auto l = lower_bound(a + 1, a + n + 1, x);
auto r = upper_bound(a + 1, a + n + 1, y);
cout << r - l << endl;
}
return 0;
}