使用Priority Queue返回Java中的中间值

时间:2014-07-29 00:41:40

标签: java queue priority-queue

我目前只是遇到了一个问题,让我说我想找到用户输入的中间值,是否有一个Java函数我可以 peek 或< em>返回中间值?


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());    
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

当然,假设“中间”是指“中位数”。如果您的意思是“卑鄙”,那么您使用的是错误的数据结构:您应该使用数组,对其进行排序并评估(array[0]+array[last])/2