我到处搜索找到第二大数字的解决方案,但我在所有站点中都找到了一个解决方案,这是错误的。
我找到的代码:
public static void main(String[] args) {
int arr[] = { 1, 23, 47, 81, 92, 88, 52, 48, 56, 66, 65, 76, 71, 85,
49, 53, 56, 61, 65, 84 };
secondLargeNumber(arr);
}
public static void secondLargeNumber(int[] arr) {
int largest = arr[0];
int secondLargest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest) {
secondLargest = arr[i];
}
}
System.out.println("second largest in array is:" + secondLargest);
}
代码工作正常,但如果我将输入序列更改为:
int arr[] = { 11, 10, 11, 2, 3, 4, 5, 6, 7, 8};
输出将是:
second largest in array is:11
我真的不知道该怎么办!