获得双阵列的最大的k个元素 [英] Getting the largest k elements of a double array

查看:140
本文介绍了获得双阵列的最大的k个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在面临这个问题,这是一种:

The problem I am facing is this one:

的数组双期从我想要保持顶部 K 更大的价值。

I have an array of doubles from which I want to keep the top k greater values.


  1. 我见过一些涉及实施 Arrays.sort 。例如在<一href=\"http://stackoverflow.com/questions/215271/sort-arrays-of-primitive-types-in-descending-order\">this例如,相对的问题,建议使用这种方法。

  2. 由于我只对第一个感兴趣氏/ code>元素中我也尝试了 MinMaxPriorityQueue 。我创建了一个 MinMaxPriorityQueue MAXIMUMSIZE

  1. I have seen some implementations involving Arrays.sort. For example in this example with relative issue it is suggested to use this approach.
  2. Since I am only interested in the first k elements I have also experimented with MinMaxPriorityQueue. I have created a MinMaxPriorityQueue with a maximumSize:

当然有再次自动装箱。

Builder<Comparable> builder = MinMaxPriorityQueue.maximumSize(maximumSize);
MinMaxPriorityQueue<Double> top2 = builder.create();

的问题是,该顺序是升序一个它是一个我想的是相反的。所以我不能使用这种方式。

The problem is that the order is the ascending one that it's the opposite of the one I want. So I cannot use it this way.

要陈述问题真实参数我的阵列是关于 50 元素长,我有兴趣到顶部 K = 5 元素。

To state the problem's real parameters my arrays is about 50 elements long and I am interested in up to the top k = 5 elements.

那么,有没有办法使用第二种方法来绕过这个问题?我应该留在第一个,即使我并不真正需要的所有元素进行排序?你知道,如果在速度性能有任何显著差异(我将在很多情况下使用此所以这是需要的速度在哪里)?是否有任何其他解决方案,我可以使用?

So is there any way to bypass this problem using the second approach? Should I stay with the first one even though I don't really need all elements sorted? Do you know if there is any significant difference in speed performance (I will have to use this in a lot of situations so that's where the speed is needed)? Is there any other solution I could use?

至于性能,我知道我可以在理论上检查自己,但我有点出来的时候,如果有人有任何解决方案,我很高兴听到它(或反正阅读)。

As for the performance, I know I can theoretically check it myself but I am a bit out of time and if someone have any solution I am happy to hear it (or read it anyway).

推荐答案

如果你只喜欢50个元素,在我的评论所指出的,只是有点它,并采取最后的 K 元素。这2只行:

If you only have like 50 elements, as noted in my comment, just sort it and take the last k elements. It's 2 lines only:

public static double[] largests(double[] arr, int k) {
    Arrays.sort(arr);
    return Arrays.copyOfRange(arr, arr.length - k, arr.length);
}

此修改(排序)原始数组。如果你希望你的原始数组修改,你只需要+1行:

This modifies (sorts) the original array. If you want your original array unmodified, you only need +1 line:

public static double[] largests2(double[] arr, int k) {
    arr = Arrays.copyOf(arr, arr.length);
    Arrays.sort(arr);
    return Arrays.copyOfRange(arr, arr.length - k, arr.length);
}

这篇关于获得双阵列的最大的k个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆