【问题标题】:how to find-the-number-of-elements-greater-than-k-in-a-sorted-array?如何在排序数组中找到大于 k 的元素数?
【发布时间】:2019-04-28 23:43:29
【问题描述】:

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

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

}

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

【问题讨论】:

  • 嗨!我用不同的数组运行你的代码,就像@Jakubeeee 提议的那样,它毫无例外地完成了。你能写下你正在测试的数字吗?发送。顺便说一句,while(start>=end) 循环并不完全正确,因为有时甚至不执行代码。

标签: java binary-search


【解决方案1】:

您可以使用流 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2015-08-22
    相关资源
    最近更新 更多