如何找到元素数量大于k的分类数组?

问题描述 投票:1回答:1

我是数据结构和算法的完整菜鸟,这是我第一次尝试使用二进制搜索算法解决问题。

我尝试做典型的二进制搜索策略来检查中间元素是否大于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;
    }

}

我只是得到一个错误说数组出界异常。有人可以解释一下我做错了什么?谢谢 !

java binary-search
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.