Given a non-empty array of integers,returnThe third maximum number in ThisArray. If It does not exist,returnThe maximum number. The time complexity must is in O (n). Example1: Input: [3, 2, 1]output:1explanation:the Third Maximum is1. Example2: Input: [1, 2]output:2explanation:the Third maximum does not exist, so the maximum (2) is returned instead. Example3: Input: [2, 2, 3, 1]output:1Explanation:note The third maximum here means the third maximum distinct number. Both numbers with value2 is both considered as second maximum.
My Solution:
1 Public classSolution {2 Public intThirdmax (int[] nums) {3 LongFstmax =Long.min_value;4 LongSndmax =Long.min_value;5 LongThirdmax =Long.min_value;6 for(Longeach:nums) {7 if(Each >Fstmax) {8 Longtemp =Fstmax;9Fstmax =Each ;Teneach =temp; One } A if(Each<fstmax && each>Sndmax) { - Longtemp =Sndmax; -Sndmax =Each ; theeach =temp; - } - if(Each<fstmax && Each<sndmax && each>Thirdmax) { -Thirdmax =Each ; + } - } + returnThirdmax==long.min_value? (int) Fstmax: (int) Thirdmax; A } at}
Highest votes in discussion
1 Public intThirdmax (int[] nums) {2 intMax, Mid, small, count;3max = Mid = small =Integer.min_value;4Count = 0;//Count How many top elements has been found.5 6 for(intx:nums) {7 //Skip Loop if Max or mid elements is duplicate. The purpose is to avoiding right shift.8 if(x = = Max | | x = =mid) {9 Continue;Ten } One A if(X >max) { - //Right shift -small =mid; theMID =Max; - -Max =x; -count++; +}Else if(X >mid) { - //Right shift +small =mid; A atMID =x; -count++; -}Else if(x >= Small) {//if small duplicated, that ' s find, there's no shift and need to increase count. -small =x; -count++; - } in } - to //"Count" is the used for checking whether found top 3 maximum elements. + if(Count >= 3) { - returnSmall; the}Else { * returnMax; $ }Panax Notoginseng}
Leetcode:third Maximum Number