Suponga que todos los números de la matriz son enteros no negativos y que todos los números son únicos.
Copie el código de código de la siguiente manera:
matriz de paquetes;
clase pública SecondMaxElem {
público estático int getSecondMaxElem (int [] matriz) {
if(matriz == nulo || matriz.longitud <= 1) {
devolver -1;
}
int max = matriz[0] > matriz[1] ? matriz[0] : matriz[1];
int secMax = matriz[0] + matriz[1] - máx;
int len = matriz.longitud;
para(int i = 2; i < len; i++) {
int cur = matriz[i];
si(cur > secMax) {
segMax = cur;
if(secMax > max) { // intercambiar
int temp = segMax;
segMax = máx;
máx = temperatura;
}
}
}
devolver segMax;
}
público estático int getSecondMaxElem2 (int [] matriz) {
if(matriz == nulo || matriz.longitud <= 1) {
devolver -1;
}
int max = matriz[0] > matriz[1] ? matriz[0] : matriz[1];
int secMax = matriz[0] + matriz[1] - máx;
int len = matriz.longitud;
para(int i = 2; i < len; i++) {
int cur = matriz[i];
si(cur > máx) {
segMax = máx;
máx = actual;
}
else if(cur > secMax && cur < max) {
segMax = cur;
}
demás {
// En otros casos, el valor máximo y el segundo valor máximo permanecen sin cambios y se puede dibujar un eje de coordenadas.
}
}
devolver segMax;
}
público estático vacío principal (String [] argumentos) {
int[] matriz = nuevo int[] { };
/*System.out.println("Algoritmo 1: " + getSecondMaxElem(matriz));
System.out.println("Algoritmo 2: " + getSecondMaxElem2(matriz));
matriz = nuevo int[] { 2 };
System.out.println("Algoritmo 1: " + getSecondMaxElem(matriz));
System.out.println("Algoritmo 2: " + getSecondMaxElem2(matriz));*/
matriz = nuevo int[] { 2, 3, 1, 6, 7, 5, 9 };
System.out.println("Algoritmo 1: " + getSecondMaxElem(matriz));
System.out.println("Algoritmo 2: " + getSecondMaxElem2(matriz));
/*matriz = nuevo int[] { 1, 2, 3, 3, 4, 5, 5 };
System.out.println("Algoritmo 1: " + getSecondMaxElem(matriz));
System.out.println("Algoritmo 2: " + getSecondMaxElem2(matriz));*/
}
}