如何摆脱此消息?
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));
}
}
使用非原始PriorityQueue
,并将减法结果强制转换为int
:
Queue<Long> heap = new PriorityQueue<>( (a,b)-> (int) (b - a) );
当然,如果长度的差异超过int
的范围,这将产生意想不到的结果。
它更容易使用:
Queue<Long> heap = new PriorityQueue<>(Comparator.reverseOrder());