题解 | #查找#
查找
https://www.nowcoder.com/practice/8e0c0e8c78944847be9bca54b59d713f
#include<bits/stdc++.h>
using namespace std;
int main(){
set<int>s;
//write your code here......
int n,m,temp=0;
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>temp;
s.insert(temp);//有序存储bucfu
}
// for(int i=0;i<m;i++){
// cin>>temp;
// set<int>::iterator it=s.upper_bound(temp);
// if(it==s.end()){
// cout<<-1<<endl;
// }
// else{
// cout<<*it<<endl;
// }
// }
int flag=0;
set<int>::iterator it;
while(m--){
cin>>temp;
it=s.find(temp);
if(it==s.end()){
s.insert(temp);
it=s.find(temp);
flag=1;
}
it++;
if(it==s.end())cout<<-1<<endl;
else cout<<*it<<endl;
if(flag){
flag=0;
it--;
s.erase(it);
}
}
return 0;
}
注意set的特性是有序不重复储存。熟练使用set的find方法以及特性可以解这个题目。

查看4道真题和解析