How to find the second largest number in the array in time complexity O (n)?
By setting two variables, one holds the maximum value, one holds the second largest value, and by the process of finding the maximum value, the original maximum is gradually changed to the second largest value. One implementation code is as follows (Java edition):
1 /**2 * Find the second largest number of arrays in time complexity O (n)3 * @authorJiajoa4 *5 */6 Public classAlgorithm_getsecondmax {7 8 Public Static voidMain (string[] args) {9 //TODO auto-generated Method StubTen int[] data = {3,2,5,1,6,4,7}; One System.out.println (Algorithm_getsecondmax.getsecondmax (data)); A } - - //by setting two variables, one holds the maximum value, one holds the second largest value, the //by the process of finding the maximum value, the original maximum value gradually becomes the second largest value, - Public Static intGetsecondmax (int[] data) { - intFirst_max = data[0]; - intSecond_max =Integer.min_value; + for(inti=1;i<data.length;i++){ - if(data[i]>First_max) { +Second_max =First_max; AFirst_max =Data[i]; at}Else{ - if(data[i]>Second_max) -Second_max =Data[i]; - } - } - returnSecond_max; in } -}
Find the second largest number in a shaped array