gpt4 book ai didi

java - Java 查找数组中最小和第二小的值

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:09 25 4
gpt4 key购买 nike

我正在尝试创建两种方法,第一种方法用于查找对象数组中的最小值,另一种方法用于查找对象数组中的第二个最小值。

我这样写了两个

public static BanffMarathonRunner getFastestTime(BanffMarathonRunner[] runner){
if(runner.length == 0){
return null;
}
BanffMarathonRunner fastest = runner[0];
for(int i = 0; i< runner.length; i++){
BanffMarathonRunner now = runner[i];
if(now.Time < fastest.Time){
fastest = now;

}
}
return fastest;
}
public static BanffMarathonRunner getSecondFastestTime(BanffMarathonRunner[] runner){
if(runner.length == 0){
return null;
}
BanffMarathonRunner fastest = runner[0];
BanffMarathonRunner secondFastest = runner[0];
for(int i = 0; i< runner.length; i++){
BanffMarathonRunner now = runner[i];
if(now.Time < fastest.Time){
fastest = now;
for(int j = 0; j< runner.length; j++){
BanffMarathonRunner now2 = runner[j];
if(now2.Time < secondFastest.Time){

secondFastest = now2;
if(now2.Time == fastest.Time){
secondFastest = secondFastest;
}
}
}

}
}
return secondFastest;
}

我已经弄清楚如何找到最小值,我只需要找到第二小的值,但我不知道如何找到。

有什么想法吗?谢谢!

最佳答案

Arrays.sort(test);
if(test.length-2 >= 0)
System.out.println(test[test.length-2]);

关于java - Java 查找数组中最小和第二小的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499611/

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