原图出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvsehe/
解法一:
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
}
思路:从小到大排序,然后从后面开始获取数组元素即可。
解法二:
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
for (int num : nums) {
queue.add(num);
if (queue.size() > k) {
queue.poll();
}
}
return queue.peek();
}
}
思路:最小堆解决问题,将数组放到最小堆中,如果堆中的元素大于k,就将堆顶出栈,之后我们只需要取出堆顶元素就是我们想要的值。