2 条题解
-
0
P2249 【深基13.例1】查找——题解
解题思路
序列已经有序。对每个询问使用二分查找寻找第一个不小于 的位置
lower_bound。若该位置仍在数组内且值等于 ,其下标加一就是第一次出现的位置;否则不存在。复杂度分析
时间复杂度 ,空间复杂度 。
C++17 参考代码
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false);cin.tie(nullptr); int n,m;cin>>n>>m;vector<long long>a(n); for(auto &x:a)cin>>x; while(m--){ long long q;cin>>q; int p=lower_bound(a.begin(),a.end(),q)-a.begin(); cout<<(p<n&&a[p]==q?p+1:-1)<<(m?' ':'\n'); } return 0; } -
0
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false);cin.tie(nullptr); int n,m;cin>>n>>m;vectora(n); for(auto &x:a)cin>>x; while(m--){ long long q;cin>>q; int p=lower_bound(a.begin(),a.end(),q)-a.begin(); cout<<(p<n&&a[p]==q?p+1:-1)<<(m?' ':'\n'); } return 0; }
- 1
信息
- ID
- 4934
- 时间
- 5000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 3
- 已通过
- 2
- 上传者
粤公网安备44195502000195号