我是数据结构和算法的一个完整的菜鸟,这是我第一次尝试使用二进制搜索算法解决问题。
我尝试执行典型的二进制搜索策略,以检查中间元素是否大于k,然后检查其是否为增量起始索引等。
class GFG {
public static int search(int arr[], int num){
int count=0;
int start = arr[0];
int end = arr.length-1;
while(start>=end){
int mid = start+end/2;
if(arr[end]>num){
return 1;
}
else if (arr[mid]>num){
count++;
start= mid+1;
}
else{
start=mid+1;
}
}
return count;
}
}
我只是得到一个错误,说数组超出了范围的异常。有人可以解释我做错了什么吗?谢谢!
答案 0 :(得分:0)
您可以使用流api轻松实现它。示例:
int[] array = {1,2,3,4,5,6,7,8,9,10,11};
int threshold = 5;
long count = Arrays.stream(array).filter((element) -> element > threshold).count();