数组中的第 K 个最大元素,要求o(n)复杂度

如果是最小堆,可以实现目的,但是时间复杂度:o(nlgk),因为往堆中插入数据涉及调整堆。

用快速排序的思想:

public int findKthLargest(int[] nums, int k) {
List<Integer> numList = new ArrayList<>();
for (int num : nums) {
numList.add(num);
}
return quickSelect(numList, k);
}

private int quickSelect(List<Integer> nums, int k) {
// 随机选择基准数
Random rand = new Random();
int pivot = nums.get(rand.nextInt(nums.size()));
// 将大于、小于、等于 pivot 的元素划分至 big, small, equal 中
List<Integer> big = new ArrayList<>();
List<Integer> equal = new ArrayList<>();
List<Integer> small = new ArrayList<>();
for (int num : nums) {
if (num > pivot)
big.add(num);
else if (num < pivot)
small.add(num);
else
equal.add(num);
}
// 第 k 大元素在 big 中,递归划分
if (k <= big.size())
return quickSelect(big, k);
// 第 k 大元素在 small 中,递归划分
if (big.size() + equal.size() < k)
return quickSelect(small, k - (big.size() + equal.size()));
// 第 k 大元素在 equal 中,直接返回 pivot
return pivot;
}

 

posted @ 2026-03-19 22:50  MarkLeeBYR  阅读(18)  评论(0)    收藏  举报