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;
}
相关推荐
汀、人工智能12 小时前
[特殊字符] 第21课:最长有效括号
数据结构·算法·数据库架构·图论·bfs·最长有效括号
Boop_wu12 小时前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
watson_pillow13 小时前
c++ 协程的初步理解
开发语言·c++
故事和你9113 小时前
洛谷-算法1-2-排序2
开发语言·数据结构·c++·算法·动态规划·图论
Fcy64813 小时前
算法基础详解(三)前缀和与差分算法
算法·前缀和·差分
yangyanping2010813 小时前
Go语言学习之对象关系映射GORM
jvm·学习·golang
网络工程小王13 小时前
【Transformer架构详解】(学习笔记)
笔记·学习
kvo7f2JTy13 小时前
基于机器学习算法的web入侵检测系统设计与实现
前端·算法·机器学习
北风toto13 小时前
前端CSS样式详细笔记
前端·css·笔记
List<String> error_P14 小时前
蓝桥杯最后几天冲刺:暴力大法(一)
算法·职场和发展·蓝桥杯