Find the kth largest element in an unsorted array. Note that it was the kth largest element in the sorted order and not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k are always valid, 1≤k≤array ' s length.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
1 Public class Solution {2 Public int findkthlargest (intint k) {3 arrays.sort (nums); 4 return nums[nums.length-K]; 5 }6 }
Solution Two:
Maintains a minimum heap of size k, iterates through the array, and returns the top element of the smallest heap as the K-large element.
1 Public classSolution {2 Public intFindkthlargest (int[] Nums,intk) {3priorityqueue<integer> q =NewPriorityqueue<integer> (k+1);4 for(intn:nums) {5 Q.offer (n);6 if(Q.size () >k) Q.poll ();7 }8 returnQ.poll ();9 }Ten}
Solution Three: See also use Quickseleck do O (n), two brushes and try again.
215. Kth largest Element in an Array Java solutions