Smaller or equal elements

Given an sorted array A of size N. Find number of elements which are less than or equal to B.

 

int Solution::solve(vector<int> &A, int B) {
    int start=0;
    int ans=0;
    int end=A.size()-1;
    
    while(start<=end)
    {
        int mid=(end+start)/2;
        
       if(A[mid]<=B)
       {
           ans=mid+1;
           start=mid+1;
       }
       else{
           end=mid-1;
       }
    }
    return ans;
}

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!