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;
}
相关推荐
BothSavage8 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn8 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽10 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
郝学胜_神的一滴10 小时前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
见过夏天1 天前
C++ 基础入门完全指南
c++
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术1 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六1 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程