我怎么可以找到N个最大的m个用Java 8?可以找到、我怎么、最大、Java

2023-09-11 04:51:14 作者:薄荷微光都很凉。

IntStream可能是一个最简单的方法,但我只能拿起最小的m个,如下:

IntStream may be a the easiest way but I can only pick up smallest M numbers as below:

public class Test {
    private static final int[] arr = {5, 3, 4, 2, 9, 1, 7, 8, 6};

    public static void main(String[] args) throws Exception {
        System.out.println(Arrays.asList(IntStream.of(arr).sorted().limit(5).boxed().toArray()));
    }
}

顺便说一句,考虑到算法的复杂度,并假设N >>男,一排序+限价的做法只是有一个复杂性为O(N日志(N))。

btw, considering algorithm complexity and assuming N >> M, a "sorted + limit" approach just have a complexity of O(N log(N)).

我觉得最好的复杂性可能达到O(N日志(M)),但我不知道Java的8是否有这种流的方法或收藏家。

I think the best complexity may reach to O(N log(M)) but I do not know whether Java 8 has this kind of stream methods or collectors.

推荐答案

如果你必须使用流:

IntStream.of(arr).sorted().skip(N-M)

否则,使用的PriorityQueue 和自己写一个反相比较。插入会的 O(N(日志(N))的和去除M个元素将是 O(M(日志(N))的。你问不什么,但也许足够接近。

Otherwise use a PriorityQueue and write yourself an inverting Comparator. Insertion will be O(N(log(N)) and removal of M elements will be O(M(log(N)). Not what you asked for, but maybe close enough.