题目
求数组中第二大的数
思路
第一遍求 max1;第二遍求 max2 满足 a[i]<max1 的最大,或 a[i]>max2 && a[i]<max1;全相等时要按题面约定。
解题分析
一遍扫描维护第一大、第二大(互异时)。遇到比 first 大的,second 取原 first 再更新 first。有重复最大值时第二大可能等于第一大,题目若要求严格第二大需另判。
完整程序
import java.io.*;
public class Main {
public static void main(String[] args) {
int n = 5;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = 3;
int first = a[0], second = a[1];
if (second > first) {
int t = first;
first = second;
second = t;
}
for (int i = 2; i < n; i++) {
if (a[i] > first) {
second = first;
first = a[i];
}
else if (a[i] > second) second = a[i];
}
System.out.println(second);
}
}
运行示例
输出:
7