Noob approach but works!


#1

This solution uses the normal binary search algorithm until the search element is found for the first time. It then linearly decreases the size of the search space to count the number of occurence.

int Solution::findCount(const vector &v, int B) {
int start = 0;
int end = v.size()-1;

while(start<=end){
    int mid = (start+end)/2;

    if(v[mid] < B)
        start = mid+1;
    else if(v[mid]>B)
        end = mid-1;
    else
        break;
}

while(start<=end){
    if(v[start]==B && v[end]==B)
        return end-start+1;
    else if(v[start]==B)
        end--;
    else if(v[end]==B)
        start++;
    else{
        start++;
        end--;
    }
}
return 0;

}