假设该数组所有数都为非负整数,且所有数字都各自不同。
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 {
// 其他情况最大值和第二大值不变,可以画一个坐标轴
}
}
return secMax;
}
public static void main(String[] args) {
int[] array = new int[] { };
/* System.out.println("算法1: " + getSecondMaxElem(array));
System.out.println("算法2: " + getSecondMaxElem2(array));
array = new int[] { 2 };
System.out.println("算法1: " + getSecondMaxElem(array));
System.out.println("算法2: " + getSecondMaxElem2(array));*/
array = new int[] { 2, 3, 1, 6, 7, 5, 9 };
System.out.println("算法1: " + getSecondMaxElem(array));
System.out.println("算法2: " + getSecondMaxElem2(array));
/* array = new int[] { 1, 2, 3, 3, 4, 5, 5 };
System.out.println("算法1: " + getSecondMaxElem(array));
System.out.println("算法2: " + getSecondMaxElem2(array));*/
}
}