Java:抢得第二高

Kar*_*rem 0 java

可能重复:
查找数组中第二高的数字

我有这个,

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

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

And*_*ndy 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;
}
Run Code Online (Sandbox Code Playgroud)