Solution
- Initialize max and second_max with the lowest possible value
Integer.MIN_Value
- Then go through your array and check for each element if it is greater then the
max_value
-> When yes reassign your max_value with a[i] and reassign your second_max_value with max_malue
if (a[i] > max) {
temp = max;
max = a[i];
second_max = temp;
Then check if your a[i] is greater then your second_max_value and not equal to your max_value . If yes reassign your second_max_value with a[i]
a[i] > second_max && a[i] != max
Last but not least check if second_max is equal to the initial value
If yes then there is no second highest Value in your Array. Example Arrays for this case
{5, 5, 5}, {1}
@Thanks to Henry
Here the Code
public static void main(String[] args) {
int[] a = { 6, 8, 2, 4, 3, 1, 5, 7 };
int max = Integer.MIN_VALUE;
int second_max = Integer.MIN_VALUE;
int temp;
for (int i = 0; i < a.length; i++) {
if (a[i] > max) {
temp = max;
max = a[i];
second_max = temp;
} else if (a[i] > second_max && a[i] != max) {
second_max = a[i];
}
}
if (second_max == Integer.MIN_VALUE) {
System.out.println("No Second Highest value");
} else {
System.out.println(second_max);
}
}
Output
7
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…