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;
}
相关推荐
二哈赛车手13 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
吃好睡好便好13 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
仰泳之鹅14 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
nashane14 小时前
HarmonyOS 6学习:CapsLock键失效诊断与长截图完整实现指南
学习·华为·harmonyos
于小猿Sup15 小时前
VMware在Ubuntu22.04驱动Livox Mid360s
linux·c++·嵌入式硬件·自动驾驶
xian_wwq16 小时前
【学习笔记】AGC协调控制系统概述
笔记·学习
x_yeyue16 小时前
三角形数
笔记·算法·数论·组合数学
憧憬成为java架构高手的小白17 小时前
docker学习笔记(基于b站多个视频学习)【未完结】
笔记·学习
Mr. zhihao17 小时前
深入解析redis基本数据结构
数据结构·数据库·redis
辰海Coding17 小时前
MiniSpring框架学习-完成的 IoC 容器
java·spring boot·学习·架构