Assume that all numbers in the array are non-negative integers, and all numbers are unique.
Copy the code code as follows:
package array;
public class SecondMaxElem {
public static int getSecondMaxElem(int[] array) {
if(array == null || array.length <= 1) {
return -1;
}
int max = array[0] > array[1] ? array[0] : array[1];
int secMax = array[0] + array[1] - max;
int len = array.length;
for(int i = 2; i < len; i++) {
int cur = array[i];
if(cur > secMax) {
secMax = cur;
if(secMax > max) { // swap
int temp = secMax;
secMax = max;
max = temp;
}
}
}
return secMax;
}
public static int getSecondMaxElem2(int[] array) {
if(array == null || array.length <= 1) {
return -1;
}
int max = array[0] > array[1] ? array[0] : array[1];
int secMax = array[0] + array[1] - max;
int len = array.length;
for(int i = 2; i < len; i++) {
int cur = array[i];
if(cur > max) {
secMax = max;
max = cur;
}
else if(cur > secMax && cur < max) {
secMax = cur;
}
else {
// In other cases, the maximum value and the second maximum value remain unchanged, and a coordinate axis can be drawn.
}
}
return secMax;
}
public static void main(String[] args) {
int[] array = new int[] { };
/*System.out.println("Algorithm 1: " + getSecondMaxElem(array));
System.out.println("Algorithm 2: " + getSecondMaxElem2(array));
array = new int[] { 2 };
System.out.println("Algorithm 1: " + getSecondMaxElem(array));
System.out.println("Algorithm 2: " + getSecondMaxElem2(array));*/
array = new int[] { 2, 3, 1, 6, 7, 5, 9 };
System.out.println("Algorithm 1: " + getSecondMaxElem(array));
System.out.println("Algorithm 2: " + getSecondMaxElem2(array));
/*array = new int[] { 1, 2, 3, 3, 4, 5, 5 };
System.out.println("Algorithm 1: " + getSecondMaxElem(array));
System.out.println("Algorithm 2: " + getSecondMaxElem2(array));*/
}
}