维护一个max值,维护一个seMax值
当a[i]大于max时,将max赋值给seMax,将a[i]赋值给max
当a[i]处于两者之间,将a[i]赋值给seMax就行
直到遍历到数组的最后
程序如下:
public static void findSecondMax(int[] a) {
int max = a[0];
int seMax = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] >= max) {
seMax = max;
max = a[i];
} else if (a[i] > seMax && a[i] < max) {
seMax = a[i];
}
}
System.out.println("最大的数为:" + max);
System.out.println("第二大的数为:" + seMax);
}
本文介绍了一种高效的方法来查找数组中的最大值和第二大值。通过一次遍历,算法能够更新最大值和次大值,适用于各种大小的数组。代码示例使用Java实现,展示了如何在遍历过程中维护这两个值。

被折叠的 条评论
为什么被折叠?



