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.
Subscribe to see which companies asked this question
Hide TagsHeap Divide and ConquerHide Similar Problems(m) Wiggle Sort II (m) Top K frequent Elements
1. Quick Select algorithm:
Https://en.wikipedia.org/wiki/Quickselect
2. Priority Queue:
Public classSolution { Public intFindkthlargest (int[] Nums,intk) {Priorityqueue<Integer> PQ =NewPriorityqueue<integer>(k); for(inti:nums) { if(Pq.size () <k) Pq.add (i); Else if(Pq.peek () <i) {pq.remove (); Pq.add (i); } } returnPq.peek (); }}
215. Kth largest Element in an Array