gpt4 book ai didi

java - 返回值数组中的两个最大整数

转载 作者:搜寻专家 更新时间:2023-11-01 01:03:05 25 4
gpt4 key购买 nike

我试图从我的 int 数组中返回两个最大的整数。我能够返回最大和最小的罚款,但我无法让我的算法返回两个最大的罚款。非常感谢任何帮助。

请原谅我代码中的任何错误。这是一个练习环节,问题取自大学去年的考试 Material 。

这是我的代码:

public class TwoLargestIntsArray {

public static void main(String [] args){

int [] values = new int[5];

values[0] = 5;
values[1] = 10;
values[2] = 15;
values[3] = 20;
values[4] = 25;

System.out.println(twoLargest(values));
System.out.println();

}

public static int twoLargest(int values[]){

int largestA = values[0];
int largestB = values[0];

for(int i = 0; i < values.length; i++){

if(values[i] > largestA){
largestA = values[i];
}
if(values[i] < largestA){
largestB = values[i];
}

}
return largestA + largestB;
}

}

最佳答案

你可以写

public static int[] twoLargest(int values[]){
int largestA = Integer.MIN_VALUE, largestB = Integer.MIN_VALUE;

for(int value : values) {
if(value > largestA) {
largestB = largestA;
largestA = value;
} else if (value > largestB) {
largestB = value;
}
}
return new int[] { largestA, largestB };
}

关于java - 返回值数组中的两个最大整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16384472/

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