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;
}
相关推荐
载数而行5201 天前
QT的五类布局
c++·qt·学习
故事和你911 天前
sdut-程序设计基础Ⅰ-实验五一维数组(8-13)
开发语言·数据结构·c++·算法·蓝桥杯·图论·类和对象
载数而行5201 天前
QT的QString类
c++·qt·学习
像污秽一样1 天前
算法与设计与分析-习题4.2
算法·排序算法·深度优先·dfs·bfs
zl_dfq1 天前
Python学习2 之 【数据类型、运算及相关函数、math库】
学习
Storynone1 天前
【Day20】LeetCode:39. 组合总和,40. 组合总和II,131. 分割回文串
python·算法·leetcode
bu_shuo1 天前
Visual C++2010学习版(全国计算机等级二级考试版)安装记录
c++·cpp·visual c++·计算机二级
明明如月学长1 天前
AI 更新太快学不过来?我用OpenClaw打造专属AI学习工作流
算法
左左右右左右摇晃1 天前
HashMap 扩容机制
笔记
黎阳之光1 天前
【黎阳之光:以无线专网与视频孪生,赋能智慧广电与数字中国】
算法·安全·智慧城市·数字孪生