Binary Search then 2 loops to search left and right


#1

public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public int findCount(final List A, int B) {
int low = 0, high = A.size()-1, cnt=0;
while(low<=high){
int mid = low+(high-low)/2;
if(A.get(mid)==B){
cnt=1; int l=mid-1, r=mid+1;
while(l>=0&&A.get(l)==B){
cnt++;
l–;
}
while(r<A.size()&&A.get®==B){
cnt++;
r++;
}
return cnt;
}
else if(A.get(mid)<B){
low = mid+1;
}
else {
high = mid-1;
}
}
return cnt;
}
}