Assume that all numbers in the array are non-negative integers, and that all digits are different.
Copy 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 {
Other cases the maximum and the second largest value unchanged, you can draw an axis
}
}
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));
}
}