java - 使用优先级队列计算中值

标签 java collections

我正在为 coursera 相关类(class)做这项作业,并且是 Java、DS 和 Algo 的新手。我不会在这里粘贴我的整个代码。但下面是我在相关代码中遇到的问题。

因此,为了检索中位数,我使用 PriorityQueueComparator 接口(interface)。从下面的函数中,我尝试创建两个 PriorityQueue,例如对于 21 个元素,hLow 优先级队列有 11 个最小元素,而 hHigh > 具有 10 个最高元素。

public static void addToStream (int k) {
    hLow.add (k);
    if (hLow.size() > (hHigh.size() + 1)) {
        hHigh.add(hLow.poll());
    }
}

我为hLow编写的比较器函数是

hLComp = new Comparator <Integer> () {
        public int compare (Integer o1, Integer o2) {
            return o1.compareTo(o2);
        }   
    };

对于hHigh

hHComp = new Comparator <Integer> () {
        public int compare (Integer o1, Integer o2) {
            return -o1.compareTo(o2);
        }   
    };

我面临的问题是

hHigh.add(hLow.poll()) 

检索到错误的值。例如,如果第一个值是 3000,那么这就是中位数,但是当第二个值出现时,例如是 6000。然后代码进入 if 条件,之后 hHigh.peek 显示 3000 hLow.peek 显示 6000。这与我的预期相反。

最佳答案

上面的方法有问题。只要尝试 5 4 3 你就会看到。 该算法需要基本情况​​。这里解释得很好:

Find running median from a stream of integers

关于java - 使用优先级队列计算中值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11659690/

相关文章:

java - 为什么链接列表类在 macos x 上的 myeclipse 2013 pro 中没有正确显示添加方法

java - 如何将 'creating of a new instance of a fragment' 保存在变量中?

java - Struts 2,tomcat 7 上的 "Resourse not found",jdk 1.7

ruby-on-rails - 我应该如何在 Rails 中存储属性的集合?

Java 8 - reduce(0, Integer::sum) 和 reduce(0, (a, b) -> a+b) 之间的区别

java - 在实现 Comparable 接口(interface)的类中调用 collections.sort() 方法时引用的当前对象是什么?

java - Java 数组从小到大排序的方法

java - JPA "cannot be cast to java.sql.Blob"

java - void 方法的单元测试

java - 哪个 list<Object> 实现对于一次写入、读取和销毁来说是最快的?