英文:
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 '-'
    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));
    }
}
答案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<Long> heap = new PriorityQueue<>( (a,b)-> (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<Long> heap = new PriorityQueue<>(Comparator.reverseOrder());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论