【问题标题】:Using Priority Queue to return the middle value in JavaJava中使用Priority Queue返回中间值
【发布时间】:2014-07-29 00:41:40
【问题描述】:

我目前遇到一个问题,假设我想找到用户输入的中间值,Java 中有没有可以peekreturn的函数> 中间值?


import java.util.*;
public class PQueue {

    public static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {

        int arr;

        PriorityQueue<Integer> queueB = new PriorityQueue<Integer>();
        for(int j=0; j<=4; j++)
        {
            System.out.println("Input Intergers: ");
            arr = console.nextInt();
            queueB.add(arr);
        }
        System.out.print(queueB.peek());    
    }
}

【问题讨论】:

  • 为什么要使用优先队列?中间值是什么意思?
  • 哦,来吧人们。这个问题很清楚。
  • @Falmarri 我正在使用优先队列,以便预先对输入的整数进行排序。

标签: java queue priority-queue


【解决方案1】:

只需从 PQ 中弹出一半的值。最后弹出的是中间的。

N 为偶数的情况留给读者练习。

当然,这是假设“中间”是指“中位数”。如果您的意思是“平均”,则说明您使用了错误的数据结构:您应该使用数组,对其进行排序,然后计算 (array[0]+array[last])/2

【讨论】:

  • O(n)时间内可以得到最小值和最大值。
  • 或者您可以使用 Quicksort 的变体来确定中位数。
  • (array[0]+array[last])/2 不是这个意思
猜你喜欢
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2017-08-02
  • 1970-01-01
相关资源
最近更新 更多