标签:
题目:
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array‘s length.
链接: http://leetcode.com/problems/kth-largest-element-in-an-array/
题解:
找数组中第k大的元素,可以用heap,Radix sort或者Quick-Select。不过Quick-Select的Time Compleixty只有在Amorized analysis上才是O(n)。下面是使用Java自带的priority queue min-heap来完成的,算是投机取巧了。二刷要补上Radix sort以及Quick-Select
Time Complexity - O(nlogn), Space Complexity - O(k)
public class Solution { public int findKthLargest(int[] nums, int k) { // use min oriented heap, store min value at top of the heap if(nums == null || nums.length == 0) return 0; PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k); for(int i = 0; i < nums.length; i++) { if(pq.size() < k) pq.offer(nums[i]); else { if(nums[i] > pq.peek()) { pq.poll(); // remove min pq.offer(nums[i]); } } } return pq.poll(); } }
Reference:
https://leetcode.com/discuss/38336/solutions-partition-priority_queue-multiset-respectively
https://leetcode.com/discuss/45627/ac-clean-quickselect-java-solution-avg-o-n-time
https://leetcode.com/discuss/36913/solutions-java-having-worst-time-complexity-with-explanation
https://leetcode.com/discuss/36991/java-quick-select
215. Kth Largest Element in an Array
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/4982861.html