题解 | 【模板】集合操作

【模板】集合操作

https://www.nowcoder.com/practice/a37b91f84cdf490b8d8b990794211135

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,opt,x;
    set<int> s;
    cin>>n;
    while(n--){
        cin>>opt;
        if(opt==1){
            cin>>x;
            s.insert(x);
        }
        else if(opt==2){
            cin>>x;
            s.erase(x);
        }
        else if(opt==3){
            cin>>x;
            if(s.count(x)){
                cout<<"YES"<<endl;
            }
            else{
                cout<<"NO"<<endl;
            }
        }
        else if(opt==4){
            cout<<s.size()<<endl;
        }
        else if(opt==5){
            cin>>x;
            auto it=s.lower_bound(x);//遍历到大于等于x的第一个位置
            if(it==s.begin()){
                cout<<-1<<endl;//如果所有元素都大于x,输出-1
            }else{
                --it;
                cout<<*it<<endl;//如果x是中间位置,则在大于等于x的第一个位置迁移找到前驱
            }
        }
        else if(opt==6){
            cin>>x;
            auto it=s.upper_bound(x);//遍历到大于x的第一个位置
            if(it==s.end()){
                cout<<-1<<endl;//如果x是最大值,输出-1
            }
            else
            {
                cout<<*it<<endl;//如果x是中间值,则直接输出大于x的第一个值
            }
        }
    }
    return 0;
}

全部评论

相关推荐

爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-19 10:38
实力求职者:真的绷不住了,第一张霸总人设,第二张求生欲拉满
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务