Why this approach does not work?


#1

int Solution::findCount(const vector &A, int B) {

if(A.size()==1&&A[0]!=B) return 0;

int l = 0;
int h = A.size()-1;
int mid = l + (h-l)/2;

while(l<=h){
    if(A[mid]==B){
        int i = 0;
        int j = 1;
        while(A[mid+i]==B){
            i++;
            
        }
        
        while(A[mid-j] == B){
            j++;
        }
    
        return i+j-1;
    }
    
    else if (A[mid]<B){
        l = mid+1;
        mid = l + (h-l)/2;
        
        continue;
    }
    
    else if(A[mid]>B){
        h = mid -1;
        mid = l + (h-l)/2;
    }
    
}

return 0;

}


#2

if all the elements in the array are same and equal to the target value then your code will first find the mid term and it will iterate over whole array and the time complexity in that case will be O(n) and not O(logn) that’s why your approach doesn’t work