c++ - 涉及上限和下限的问题
问题描述
在排序数组中查找给定数字的最后一次和第一次出现的位置。如果数字不存在,则将下限和上限打印为 -1。我编写了如下代码,但我无法通过所有测试用例。谁能告诉我为什么?
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> v;
int n,num,q,find;
cin>>n;
v.reserve(n);
for(int i=0;i<n;i++){
cin>>num;
v.push_back(num);
}
sort(v.begin(),v.end());
cin>>q;
while(q--){
cin>>find;
auto lb=lower_bound(v.begin(),v.end(),find);
auto ub=upper_bound(v.begin(),v.end(),find);
if(lb==v.end() || v.empty()){
cout<<-1<<" "<<-1<<endl;
}
else{
cout<<lb-v.begin()<<" "<<ub-v.begin()-1<<endl;
}
}
return 0;
}
解决方案
std::lower_bound(first, last, value)
没有找到等于 的元素value
,它找到了下界(不小于 的第一个元素value
),顾名思义。例如,对于范围1 3 5
和目标值2
,它将返回指向的迭代器3
。
要检查元素是否存在于数组中,您可以编写
auto pos = std::lower_bound(first, last, value);
if (pos != last && *pos == value)
// ...
还应该注意的是,两次调用std::lower_bound
和std::upper_bound
可以替换为一次调用std::equal_range
。
推荐阅读
- python-3.x - 需要将多个变量传递给有效负载变量
- sql-server - Incorrect syntax near ..... when using with statement
- pandas - Docker build failing while installing pandas in docker in python2.7-alpine
- php - Laravel eloquent builder, 3 tables with relations
- c++ - What goes wrong when passing a std::sub_match as argument to a std::thread?
- javascript - How to filter JSON with nested object
- hibernate - 服务列表问题
- azure-cognitive-search - Azure 搜索斯堪的纳维亚规范化
- discord.py - 我如何将嵌入值与“
" in discord bot
- php - Laravel:路由:缓存不使用子目录中的文件