Java:抢第二高[重复项]

问题描述

|                                                                                                                   这个问题已经在这里有了答案:                                                      

解决方法

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;
}
    ,使用自定义对数组排序
Comparator
(复制数组 如果您无法对原件进行排序) 选择排序数组的最后一项:
// hopefully you have checked in advance that there is more than one item
return sortedDices[sortedDices.length-2];