在优先队列中,二元运算符“-”对于错误的操作数类型。

huangapple go评论65阅读模式
英文:

bad operand types for binary operator '-' in Prioritiy Queue

问题

如何去掉这个消息?
bad operand types for binary operator '-'
    Queue<Long> heap = new PriorityQueue( (a,b)->b - a );
first type:  Object
second type: Object
import java.util.*; 
class solve {

    static long minCost(long arr[], int n) {

        Queue<Long> heap = new PriorityQueue( (a,b)-> b - a );

        long ans = 0;

        for( long i : arr )
            heap.add(i);

        while(!heap.isEmpty()){
            long f = heap.poll();

            if( heap.isEmpty()) return f+ans;

            long s = heap.poll();
            ans += f+s;
            heap.add(f+s);    
        }

        return ans;
    }
    public static void main(String[] args) {
        long a[] = {4, 3, 2, 6};
        System.out.println(minCost(a, 4));

    }
}
英文:

How do I get rid off this message?

bad operand types for binary operator &#39;-&#39;
    Queue&lt;Long&gt; heap = new PriorityQueue( (a,b)-&gt;b - a );
first type:  Object
second type: Object
import java.util.*; 
class solve {

    static long minCost(long arr[], int n) {
        
        Queue&lt;Long&gt; heap = new PriorityQueue( (a,b)-&gt; b - a );
        
        long ans = 0;
        
        for( long i : arr )
            heap.add(i);
            
        while(!heap.isEmpty()){
            long f = heap.poll();
            
            if( heap.isEmpty()) return f+ans;
            
            long s = heap.poll();
            ans += f+s;
            heap.add(f+s);    
        }
        
        return ans;
    }
    public static void main(String[] args) {
        long a[] = {4, 3, 2, 6};
        System.out.println(minCost(a, 4));

    }
}

答案1

得分: 0

使用非原始的PriorityQueue,并将减法的结果转换为int

Queue<Long> heap = new PriorityQueue<>((a, b) -> (int) (b - a));

当然,如果长整型之间的差值超过了int的范围,这将导致意外的结果。

更简单的方法是直接使用:

Queue<Long> heap = new PriorityQueue<>(Comparator.reverseOrder());
英文:

Use non-raw PriorityQueue, and cast the result of the subtraction to int:

Queue&lt;Long&gt; heap = new PriorityQueue&lt;&gt;( (a,b)-&gt; (int) (b - a) );

Of course, this will give unexpected results if the difference in the longs exceeds the range of int.

It is easier just to use:

Queue&lt;Long&gt; heap = new PriorityQueue&lt;&gt;(Comparator.reverseOrder());

huangapple
  • 本文由 发表于 2020年9月10日 18:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63828138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定