27| 魔法封印

一、核心思路

在一个有序数组中,快速查询给定区间 [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;
}
相关推荐
桂花很香,旭很美1 小时前
Anthropic Agent 工程实战笔记(四)长任务与多 Agent
笔记·架构·agent
2501_918126911 小时前
stm32能做次声波检测器吗?
c语言·stm32·单片机·嵌入式硬件·学习
honortech1 小时前
算法题中的 mid 中点问题
算法
好好学习天天向上~~1 小时前
13_Linux_学习总结_进程终止
linux·学习
今儿敲了吗1 小时前
30| 木材加工
数据结构·c++·笔记·学习·算法
土拨鼠烧电路1 小时前
笔记08:供应链的生命线:预测、库存与韧性
人工智能·笔记
WW_千谷山4_sch1 小时前
MYOJ_7789:(洛谷P3388)【模板】割点(割顶)(tarjan算法)
c++·算法·深度优先·图论
WZ188104638691 小时前
LeetCode第131题
算法·leetcode
锅包一切1 小时前
PART7 队列
c++·学习·算法·leetcode·力扣·刷题·队列