gpt4 book ai didi

Java:抢占第二位

转载 作者:行者123 更新时间:2023-12-01 07:40:03 25 4
gpt4 key购买 nike

Possible Duplicate:
Finding the second highest number in array

我有这个,

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

获得最高值(value)。我现在想要获得第二高,我该怎么做?我不能利用这个最高的变量来获得第二高的变量吗?

最佳答案

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;
}

关于Java:抢占第二位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6127612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com