Code is not working! But why?


#1

int Solution::findCount(const vector &A, int B) {
int low,high,mid,resFirst=-1,resSecond=-1;
low=0;
high=A.size()-1;

while(low<=high)        //first index
{
    mid=floor(low+(high-low)/2);
    if(A[mid]==B)
    {
        resFirst=mid;
        high=mid-1;
    }
    else if (A[mid] < B)
        low=mid+1;
    else
        high=mid-1;
    
}
if(resFirst==-1)
    return resFirst;
high=A.size()-1;
while(low<=high)        //second index
{
    mid=floor(low+(high-low)/2);
    if(A[mid]==B)
    {
        resFirst=mid;
        low=mid+1;
    }
    else if (A[mid] < B)
        low=mid+1;
    else
        high=mid-1;
    
}

return resSecond-resFirst+1;

}


#2

before finding second index set the low value to 0 and also check for the base condition if the element is not there because from your code if element is not there first and second index will be -1 and it will return answer as 1 but it should be 0.