Problem 2 Kth Largest Element in an Array
Method 1: MaxHeap
全部放进去弄k次
public int findKthLargest(int[] nums, int k) {
// assume nums not null and empty
PriortyQueue<Integer> maxHeap = new PriortyQueue<>(Collections.reverseOrder());
for (int i = 0; i < nums.length; i++) {
maxHeap.offer(nums[i]);
}
int count = k;
while (count > 1) {
maxHeap.poll();
count--;
}
return maxHeap.peek();
}Method 2: MinHeap
先手头拿K个candidate,
然后在便利接下来n-k个,看看能不能淘汰手头不优先的
TC: O(nlogK)
SC: O(logn)
这个minHeap online的算法能优化么?如果input是一个array,arraylist一定能用heapify优化
PreviousProblem 1 K smallest In Unsorted ArrayNextProblem 3 K Cloest Value to Target in Unsorted Array
Last updated