在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
思路
1. 最小堆
- 创建一个小根堆
- 维持一个容量为k的小根堆,将数组中每个元素都添加进来,大的元素会沉入堆底,遍历结束我们得到一个包含数组中最大的k个数的堆,堆顶即为第k个最大的元素。
代码:
package test;
import java.util.PriorityQueue;
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap =
new PriorityQueue<Integer>();//创建一个小根堆,java默认小根堆
for (int n: nums) {
heap.add(n);
if (heap.size() > k)//维持容量为k
heap.poll();
}
return heap.poll();
}
}
2. 快速选择法
原理类似快排,快速排序过程中每次划分后枢纽元素的位置都被定下来了。
class Solution {
public int findKthLargest(int[] nums, int k) {
//枢纽元素的索引和nums[n-k]比较,相比如果较大则继续划分枢纽元素左边部分
//,较小划分右边部分,相等直接返回枢纽元素
return quickSelect(nums, 0, nums.length - 1, nums.length - k);
}
public int quickSelect(int[] nums, int l, int r, int t) {//寻找数组中排序后索引为t的值
int n = nums.length;
int mid = partition(nums, l, r);
if (mid == t) return nums[mid];//
else if (mid < t) {
return quickSelect(nums, mid + 1, r, t);
} else return quickSelect(nums, l, mid - 1, t);
}
public int partition(int[] nums, int l, int r) {//基于填坑法的分割函数
int p = nums[l];
while (l < r) {
while (nums[r] >= p && l < r) r--;
nums[l] = nums[r];
while (nums[l] <= p && l < r) l++;
nums[r] = nums[l];
}
nums[l] = p;
return l;//返回枢纽元素的索引
}
}
e-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode/