Find k-th largest element in an array. NoteYou can swap elements in the Arrayexamplein array [9,3,2,4,8], the 3rd largest element are 4 inarray [ , 3,4,5], the 1st largest element is 5, 2nd largest element was 4, 3rd largest element is 3 and etc. Challengeo (n) time, O (1) space
With the improved quicksort partition, the time complexity of O (n) can be achieved and no additional space is required.
Please refer to: http://en.wikipedia.org/wiki/Quickselect#Time_complexity
Quickselect uses the same overall approach as quicksort, choosing one element as a pivot and partitioning the data in Based on the pivot, accordingly as less than or greater than the pivot. However, instead of recursing to both sides, as in quicksort, Quickselect only recurses into one side–the side with th e element it is searching for. This reduces the average complexity from O (n log n) (in quicksort) to O (n) (in Quickselect).
Here's a few points to note:
1. Line 8th kth Largest element = len-k+1st smallest element
2. Line 24th, L, R after the encounter, L is in the position of the first is greater than or equal to the pivot element position, it is exchanged with pivot, pivot is placed in the position it should be
1 classSolution {2 //param k:description of K3 //param Numbers:array of numbers4 //Return:description of Return5 Public intKthlargestelement (intK, arraylist<integer>numbers) {6 //Write your code here7 if(k > Numbers.size ())return0;8 returnHelper (Numbers.size ()-k+1, numbers, 0, numbers.size ()-1); 9 }Ten One Public intHelperintK, arraylist<integer> numbers,intStartintend) { A intL=start, r=end; - intPivot =end; - while(true) { the while(Numbers.get (L) <numbers.get (pivot) && l<r) { -l++; - } - while(Numbers.get (R) >=numbers.get (pivot) && l<r) { +r--; - } + if(L = = r) Break; A Swap (Numbers, L, R); at } - Swap (numbers, l, end); L Here are the first one which is bigger than pivot and swap it with the pivot - if(l+1 = = k)returnNumbers.get (l); - Else if(L+1 < k)returnHelper (k, numbers, l+1, end); - Else returnHelper (k, numbers, start, l-1); - } in - Public voidSwap (arraylist<integer> numbers,intLintr) { to inttemp =Numbers.get (l); + Numbers.set (L, Numbers.get (R). Intvalue ()); - Numbers.set (R, temp); the } *};
Lintcode:kth largest Element