public class Test{
public static int getFirst(int[]arr,int k,int start,int end) {
if(start>end)return -1;
int mid=(start+end)/2;
if(arr[mid]k) {
if((mid>0&&arr[mid-1]!=k)||mid0) {
return mid;
}else {
end=mid-1;
}
}else if(arr[mid]>k) {
end=mid-1;
}else {
start=mid+1;
}
return getFirst(arr, k, start, end);
}
public static int getLast(int[]arr,int k,int start,int end) {
if(start>end)return -1;
int mid=(start+end)/2;
if(arr[mid]k) {
if((mid<arr.length-1&&arr[mid+1]!=k||midarr.length-1)) {
return mid;
}else {
start=mid+1;
}
}else if(arr[mid]<k) {
start=mid+1;
}else {
end=mid-1;
}
return getLast(arr, k, start, end);
}
public static int getNum(int[]arr,int k) {
int num=0;
if(arr!=null&&arr.length>0) {
int first=getFirst(arr, k, 0, arr.length-1);
int last=getLast(arr, k, 0, arr.length-1);
if(first>=0&&last>=first) {
num=last-first+1;
}
}
return num;
}
public static void main(String[] args) {
int[]arr= {2,3,4,4,4,4,4,4,5,6,7,8};
int k=4;
System.out.println(getNum(arr, k));
}
}