Java:抢得第二高

时间:2011-05-25 16:19:03

标签: java

  

可能重复:
  Finding the second highest number in array

我有这个,

       for(int i=0;i<Dices.length;i++){
        if( Dices[i].getValue() > highest ){
            highest = Dices[i].getValue();
        }
       }

获得最高价值。我现在想要获得第二高,我该怎么做?我可以利用这个最高的变量来获得第二高的值吗?

2 个答案:

答案 0 :(得分:5)

O(n)的速度如下:

// first, second, d0, d1, di all typed by whatever getValue() returns...
// This assumes you have at least two elements in your Dices array

d0 = Dices[0].getValue();
d1 = Dices[1].getValue();
if (d0 > d1) {
    first=d0;
    second=d1;
} else {
    first=d1;
    second=d0;
}

for (int i = 2; i < Dices.length; i++) {
    di = Dices[i].getValue();
    if (di > first) {
        second = first;
        first = di;
    } else if (di > second)
        second = di;
}

答案 1 :(得分:2)

  • Sort the array使用自定义 Comparatormake a copy of the array 如果你不能对原文进行排序)
  • 选择已排序数组的最后一项:

    // hopefully you have checked in advance that there is more than one item
    return sortedDices[sortedDices.length-2];