简体   繁体   English

将 Double 转换为 Key(优先级队列)

[英]Convert Double to Key (Priority queue)

I've been on an extensive search through the interwebs looking for some type of answer to my problem, but I've had no luck finding anything that can help me.我一直在通过互联网进行广泛搜索,寻找某种类型的答案来解决我的问题,但我没有找到任何可以帮助我的东西。 Basically what I wonder about is if it is possible to convert a double into a Key that then is inserted into a Priority Queue.基本上我想知道的是是否可以将双精度转换为密钥,然后将其插入优先级队列。

This is the method I'm struggling with is from a file name MedianPQ.java .这是我正在努力使用的方法来自文件名MedianPQ.java It's this one:就是这个:

public void insert(Double a){
        if (size == 0 || a.compareTo(findMedian()) == 1) minPQ.insert(a);
        else maxPQ.insert(a);
        rearrange();
        size++;
    }

The insert method in the MinPQ.java file looks like this: MinPQ.java文件中的插入方法如下所示:

public void insert(Key x) {
        // double size of array if necessary
        if (n == pq.length - 1) resize(2 * pq.length);

        // add x, and percolate it up to maintain heap invariant
        pq[++n] = x;
        swim(n);
        assert isMinHeap();
    }

And here is the insert method from MaxPQ.java这是来自MaxPQ.java的插入方法

public void insert(Key x) {

        // double size of array if necessary
        if (n == pq.length - 1) resize(2 * pq.length);

        // add x, and percolate it up to maintain heap invariant
        pq[++n] = x;
        swim(n);
        assert isMaxHeap();
    }

They are identical.它们是相同的。 Now the problem arises as public void insert(Double a) from MedianPQ.java must not be changed.现在问题出现了,因为来自MedianPQ.java public void insert(Double a)不得更改。 I have to take in a double and then insert that double into the PQ.我必须接受一个双倍然后将那个双倍插入到 PQ 中。 But the methods from MinPQ.java and MaxPQ.java only inserts a key.但是MinPQ.java and MaxPQ.java的方法只插入一个键。 Is it possible to just convert the double to a key inside the insert(Double a) method???是否可以将双精度转换为insert(Double a)方法中的键???

You should use Double as generic for MaxPQ and MinPQ .您应该使用Double作为MaxPQMinPQ的泛型。 To do this try following:为此,请尝试以下操作:

public static void main(String[] args) {
    MedianPQ<Double> median = new MedianPQ<Double>(10, 20);
    median.insert(1.1D);
    median.insert(2.2D);
}

Or或者

private MaxPq<Double> left;
private MinPq<Double> right;

Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM