Question:
Given an integer array, find out the second largest item.
Analysis:
Sort the Array (ascending) first. The second largest is the last but one? Too Young, Too, sometimes naive. It won't work if there is duplicated times. e.g. [2,5,8,3,8,7].
We can use the indicators, Li (largest item index, set to 0 initially) and Slii (second largest item IND Ex, set to-1 initially). Traverse the array, starting from the second item in the array, let lii store the largest item ' s index, slii< /c5> Store the second largest one ' s. It can complete in O(n).
Code:
Public Static intFindsecondlargest (Final int[] Array) { if(Array! =NULL&& Array.Length >= 2) { intLII = 0; intSlii =-1; for(inti = 1; i < Array.Length; i++) { if(Array[i] >Array[lii]) {Slii=lii; LII=i; } Else if(Array[i] = =Array[lii]) { Continue; } Else{slii= (Slii = =-1 | | array[slii] < array[i])?i:slii; } returnslii; } return-1; }
So far so good.
Question:
Given an integer array, find out the third largest item.
Analysis:
WTH? Use three indicators, lii, slii, tlii (third largest item index).
Public Static intFindthirdlargest (Final int[] Array) { if(Array! =NULL&& Array.Length >= 3) { intLII = 0; intSlii =-1; intTlii =-1; for(inti = 1; i < Array.Length; i++) { if(Array[i] >Array[lii]) {Tlii=slii; Slii=lii; LII=i; } Else if(Array[i] = =Array[lii]) { Continue; } Else { if(Slii = =-1) {slii=i; } Else { if(Array[i] >Array[slii]) {Tlii=slii; Slii=i; } Else if(Array[i] = =Array[slii]) { Continue; } Else{tlii= (Tlii = =-1 | | array[tlii] < array[i])?i:tlii; } } } } returntlii; } return-1; }
It smells. I ' m kind of repeating myself.
Question:
Given an integer array, find out the ith largest item.
Analysis:
WTF? Use I indicators? Write I methods? Don ' t Repeat yourself (DRY). To find out the ith largest item, we use an assistant array indicators.
Public Static intFindithlargest (Final intithFinal int[] Array) { if(Array = =NULL|| ITH < 1 | | Array.Length <ith) { return-1; } int[] Inidcators =New int[ith]; for(inti = 1; i < ith; i++) {Inidcators[i]=-1; } for(inti = 1; i < Array.Length; i++) {updateindices (i, Array,0, inidcators); } returnInidcators[ith-1]; } Private Static voidUpdateindices (Final intCurFinal int[] Array,Final intIthlii,int[] inidcators) { if(Ithlii <inidcators.length) {if(Inidcators[ithlii] = =-1) {Inidcators[ithlii]=cur; } Else if(Array[cur] >Array[inidcators[ithlii]]) { for(inti = inidcators.length-1; i > ithlii; i--) {Inidcators[i]= Inidcators[i-1]; } Inidcators[ithlii]=cur; } Else if(Array[cur] = =Array[inidcators[ithlii]]) { return; } Else{updateindices (cur, array, ithlii+ 1, inidcators); } } }
Find ith largest array in an array