排序顺序错误

时间:2017-12-08 01:16:14

标签: java priority-queue

测试用例失败:

  • 输入: [-2147483648,1,1]

  • 输出: -2147483648

  • 预期: 1

当-2147483648是第二个最大数字时,为什么输出预期为1?

public int thirdMax(int[] nums) {

    PriorityQueue<Integer> pq = new PriorityQueue(new Comparator<Integer>(){
        public int compare(Integer a, Integer b){return b-a;}
    });

    int res=0;

    for(int num : nums){
        if(!pq.contains(num)  )
            pq.add(num);

    }

    if(pq.size()<=2){
       for(int i=0; i<pq.size(); i++){
            res=pq.poll();
        }             
    }
    else {
        for(int i=0; i<3; i++){
            res=pq.poll();
        }        
    }
    return res;   
}

1 个答案:

答案 0 :(得分:1)

您的比较方法对int不正确。

而不是:

return b - a;

你应该这样做:

return Integer.compare(b, a);

int只能保存最多Integer.MAX_VALUE的值。但是,如果您执行1 - -2147483648,则结果大于Integer.MAX_VALUE,这会使其再次为负数 - 因此您会得到错误的排序顺序。基本上,return b - a;只有在您知道所有数字都是正数(或者数字不会比Integer.MAX_VALUE更远的情况下)时才是安全的。

在其他情况下,您可以使用API​​方法Integer.compare

请注意,由于您是通过整数的自然顺序的倒数进行比较,因此您还可以使用以下命令缩短代码:

PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
相关问题