C++ binary search solution


#1

int binarySearch(const vector &A, int l, int r, int B){
int mid;
while(l <= r){
mid = (l+r)/2;
if(A[mid] == B) return mid;
else if(A[mid] > B) r = mid-1;
else l = mid + 1;
}
return -1;
}

vector Solution::searchRange(const vector &A, int B) {
vector res = {INT_MAX,INT_MIN};
int mid = binarySearch(A,0,A.size(),B);
if(mid == -1){
res[0] = -1;
res[1] = -1;
return res;
}
while(mid != -1){
res[0] = min(res[0],mid);
if(mid-1 >= 0)
mid = binarySearch(A,0,mid-1,B);
else
break;
}

mid = binarySearch(A,0,A.size(),B);
while(mid != -1 ){
    //cout << mid;
    res[1] = max(res[1],mid);
    if(mid + 1 < A.size())
        mid = binarySearch(A,mid+1,A.size(),B);
    else
    break;
}

return res;

}