gpt4 book ai didi

java - 数组中最小的和第二小的

转载 作者:行者123 更新时间:2023-12-01 11:48:24 28 4
gpt4 key购买 nike

我已经查看了此处发布的答案 ( finding smallest and second smallest number ),但我无法让我的代码运行。

这是我所拥有的。

    public static void shortestTimes(int[] times){

int counter = 0;
int secondLowest = times[counter];
int min = times[counter];

for (counter = 0; counter < times.length; counter ++) {

if (times[counter] < min) {
secondLowest = min;
min = times[counter];

} else if (times[counter] < secondLowest) {
secondLowest = times[counter];
}
}

System.out.println("The fastest time was: " + min + ". And the second fastest was: " + secondLowest);
}

当我输入时:

int[] values = {1, 3, 3, 2, 5};
longestTimes(values);

我得到输出:

The fastest time was: 1. And the second fastest was: 1

为什么我的第二低数字没有改变?

最佳答案

您的第二低值没有发生变化,因为从一开始您就将 secondLowest 设置为等于values[0]处的值,这是数组中的最低值。如果我是您,我会将 minsecondLowest 都初始化为 Integer.MAX_VALUE。那么算法将按预期运行

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

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