在 Java 中查找数组中的前 N ​​项

培训教学 潘老师 7个月前 (09-23) 168 ℃ (0) 扫码查看

学习在 Java 中查找给定数组中的前 N ​​项。注意,我们应该非常清楚前N项的含义。根据我们的解释和要求,建议的解决方案可能需要进行细微的更改。

例如,在本教程中,前 N 个项目表示数组中前 N 个最大的项目。

1. 使用队列查找前 N 个项目

数据Queue结构根据元素的优先级维护元素的顺序。好处是我们可以通过自定义Comparator来决定优先级。

在给定的示例中,我们希望找到整数数组中的前 3 个最大值。

1.1. PriorityQueue

PriorityQueue是一个基于优先级堆的无界优先级队列。优先级队列的元素按照自然顺序排列,队列的头部是最小的元素。

因此,如果我们添加此队列中的整数并继续轮询项目以将其大小限制为 3,则当循环结束时,我们将在队列中获得 3 个最大的整数值。

Integer[] items = {0, 10, 30, 2, 7, 5, 90, 76, 100, 45, 55};
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(3);
for (Integer i : items) {
    priorityQueue.add(i);
    if (priorityQueue.size() > 3)
        priorityQueue.poll();
}
System.out.println("Items are : " + priorityQueue); //[76, 100, 90]

1.2. MinMaxPriorityQueue

MinMaxPriorityQueue类是Guava 集合的一部分。它是一个双端优先级队列,提供对其最小元素和最大元素的恒定时间访问,这由队列的指定比较器或自然排序决定。

当我们将解决方案与MinMaxPriorityQueue和进行比较时PriorityQueue,我们不需要执行额外的轮询操作并在每次迭代时检查队列大小。

Maven 存储库中包含 Guava 的最新版本。

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>${guava-version}</version>
</dependency>
Integer[] items = {0, 10, 30, 2, 7, 5, 90, 76, 100, 45, 55};
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(3);
MinMaxPriorityQueue<Integer> minMaxQueue =
        MinMaxPriorityQueue.orderedBy(Collections.reverseOrder())
            .maximumSize(3)
            .create();
for (Integer i : items) {
    minMaxQueue.add(i);
}
System.out.println("Items are : " + minMaxQueue); [100, 90, 76]

2. 使用Stream API

Java Stream API是一个非常有用的方法的集合,可以通过简单的方法调用执行非常复杂的任务。

为了找到 Stream 中的前 N ​​个项目,我们需要对流中的项目进行排序,并从该流中收集三个项目。

Integer[] items = {0, 10, 30, 2, 7, 5, 90, 76, 100, 45, 55};
List<Integer> top3ItemsInList = Arrays.stream(items)
                .sorted(Collections.reverseOrder())
                .limit(3)
                .collect(Collectors.toList());
System.out.println("Items are : " + top3ItemsInList); //[100, 90, 76]

3.Arrays.copyOfRange()

copyOfRange()API 将给定数组的指定范围复制到新数组中。因此,如果我们可以对数组进行排序,我们就可以轻松选择其前 3 个项目索引,因为它们肯定是前 3 个项目。

Integer[] items = {0, 10, 30, 2, 7, 5, 90, 76, 100, 45, 55};
Arrays.sort(items, Collections.reverseOrder());
Integer[] topThreeItems = Arrays.copyOfRange(items, 0, 3);
System.out.println("Items are : " + Arrays.toString(topThreeItems)); //[100, 90, 76]

4.结论

本教程教我们如何从数组中查找前 N 个项目。前 N 个项目可以是 N 个最大的项目或 N 个最小的项目。这取决于用例。

我们学习了使用队列、流和复制数组范围功能来查找项目。我们可以根据我们的需要构建更多类似的方法。

请注意,onlyPriorityQueue不会对数组进行排序,而所有其他解决方案都对已排序的数组起作用,或者它们在内部维护排序。因此,如果您希望保持前 N 项的顺序与原始数组中一样不变,请使用PriorityQueue


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/teach/9222.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】