7788: 快速查找 二分查找/迭代器指针
描述
有n个数字,a1,a2,...,an。
给出左右两个端点l和r,你的任务找到有多少个数字在l和r之间(包括端点)。
输入
输入的第一行有一个n(1≤n≤105)。
第二行包含n个数字,a1,a2,...,an(1≤a≤109);
第三行有一个k(1≤k≤105)。
接下来k行,每行有两个数字l和r(1≤l≤r≤109)。
输出
只有一行输出,有k个整数,每个数之间有一个空格。
样例输入
5
10 1 10 3 4
4
1 10
2 9
3 4
2 2
样例输出
5 2 2 0
一开始想着用map+双指针,还是太慢了,看了看题解才知道要用二分的统计
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<ll> a(n); for(int i = 0; i < n; i++) cin >> a[i]; // Sort the array for binary search sort(a.begin(), a.end()); int k; cin >> k; ll l, r; cin >> l >> r; // Use binary search to find the positions of l and r vector<ll>::iterator l_it = lower_bound(a.begin(), a.end(), l); vector<ll>::iterator r_it = upper_bound(a.begin(), a.end(), r); // Calculate the number of elements between l and r int count = distance(l_it, r_it); cout << count; k--; while(k--) { ll l, r; cin >> l >> r; // Use binary search to find the positions of l and r l_it = lower_bound(a.begin(), a.end(), l); r_it = upper_bound(a.begin(), a.end(), r); // Calculate the number of elements between l and r int count = distance(l_it, r_it); cout << " " << count; } return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现