美文网首页
二分查找大于等于

二分查找大于等于

作者: help_youself | 来源:发表于2022-07-06 18:23 被阅读0次
    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    using namespace std;
    class Solution {
    public:
        int binary_search(std::vector<int>&num,int left,int right,int t){
            while(left<=right){
                int mid=(left+right)/2;
                if(t==num.at(mid)){
                    return mid;
                }else if(num.at(mid)<t){
                    left=mid+1;
                }else{
                    right=mid-1;
                }
            }
            return -1;
        }
        int locate_geq(std::vector<int> &num,int t){
            int n=num.size();
            int left=0,right=n-1;
            if(num[left]>=t){
                return 0;
            }
            if(num[right]<t){
                return -1;
            }
            while(left<right){
                int mid=(right+left)/2;
                if(num.at(mid)>=t){
                    right=mid;
                }else{
                    left=mid+1;
                }
            }
            return left;
        }
    };
    int main(){
        std::vector<int> data={-10,-8,1,3,5,6};
        std::sort(data.begin(),data.end());
        Solution so;
        int r=so.locate_geq(data,6);
        std::cout<<r<<std::endl;
        r=so.binary_search(data,0,data.size()-1,3);
        std::cout<<r<<std::endl;
        return 0;
    }
    

    [1] C++STL中的upper_bound()函数的使用

    相关文章

      网友评论

          本文标题:二分查找大于等于

          本文链接:https://www.haomeiwen.com/subject/pvvybrtx.html