Question:
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.
原题链接:https://leetcode.com/problems/kth-largest-element-in-an-array/description/
Java优先队列:
参考:https://blog.csdn.net/x_i_y_u_e/article/details/46381481
构造函数和API:
构造方法摘要 | |
PriorityQueue() | |
PriorityQueue(Collection<? extends E> c) | |
PriorityQueue(int initialCapacity) | |
PriorityQueue(int initialCapacity, Comparator<? super E> comparator) | |
PriorityQueue(PriorityQueue<? extends E> c) | |
PriorityQueue(SortedSet<? extends E> c) |
方法摘要 | ||
boolean | ||
void | clear() | |
Comparator<? super E> | comparator() | |
boolean | ||
iterator() | ||
boolean | ||
peek() | ||
poll() | ||
boolean | ||
int | size() | |
Object[] | toArray() | |
| toArray(T[] a) |
思路:
可以使用优先队列的数据结构,维护一个有K个数的最大堆。遍历完数组之后,就可返回堆的头部元素,即使第K大的数。
参考:https://segmentfault.com/a/1190000003704825
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> que = new PriorityQueue<Integer> ();
for (int i = 0; i < nums.length; i++)
{
que.add(nums[i]);
if(que.size() > k)
que.poll();
}
return que.poll();
}
}
博主学习记录,转载请注明出处,有错望指正,谢谢~^-^