【问题标题】:bad operand types for binary operator '-' in Prioritiy Queue [duplicate]优先级队列中二元运算符“-”的错误操作数类型[重复]
【发布时间】:2020-09-10 10:52:18
【问题描述】:

我如何摆脱这条消息?

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

    }
}

【问题讨论】:

标签: java collections queue priority-queue


【解决方案1】:

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

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

当然,如果longs的差异超过int的范围,这会产生意想不到的结果。

使用起来更简单:

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

【讨论】:

  • 即使对于int 输入,两个值之间的距离也可能大于int 值空间。这就是为什么通常不应该将减号用作比较器功能的原因。如果你不使用已经存在的Comparator.reverseOrder(),你可以使用(a,b)-&gt;Long.compare(b, a)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多