我是数据结构和算法的完整菜鸟,这是我第一次尝试使用二进制搜索算法解决问题。
我尝试做典型的二进制搜索策略来检查中间元素是否大于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;
}
}
我只是得到一个错误说数组出界异常。有人可以解释一下我做错了什么?谢谢 !
您可以使用流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();