Implementation of C lower_bound

后端 未结 8 1451
北恋
北恋 2020-12-12 18:48

Based on the following definition found here

Returns an iterator pointing to the first element in the sorted range [first,last) which does not com

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 19:05

    Example if this is the given array

    1 2 3 3 4

    and different values of x is

    3 then firstOccurance will be 2 and lastOccurance will be 3

    2 then firstOccurance will be 1 and lastOccurance will be 1

    10 then firstOccurance will be -1 and lastOccurance will be -1

    int firstOccurance(vector& arr, int x){
            int low = 0;
            int high = arr.size();
            int ans=-1;
            while(low<=high){
                int mid = (low+high)/2;
                if(arr[mid]==x)     ans=mid;
                if(arr[mid]>=x)     high=mid-1;
                else    low = mid+1;
            }
            return ans;
        }
    
    
    int lastOccurance(vector& arr, int x){
        int low = 0;
        int high = arr.size();
        int ans=-1;
        while(low<=high){
            int mid = (low+high)/2;
            if(arr[mid]==x)     ans=mid;
            if(arr[mid]<=x)     low=mid+1;
            else    high = mid-1;
        }
        return ans;
    }
    

提交回复
热议问题