215.数组中的第k个最大元素
题目描述
Leetcode:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
在未排序的数组中找到第 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 ≤ 数组的长度。
解题思路
思路一:小顶堆,堆顶存放第k大元素
思路二:快速排序的partition()
java代码
排序
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> pq = new PriorityQueue<>(); //小顶堆
for(int val : nums){
pq.add(val);
if(pq.size() > k) //维护堆的大小为k
pq.poll();
}
return pq.peek();
}
}
快速排序
class Solution {
public int findKthLargest(int[] nums, int k) {
k = nums.length - k;
int l = 0, h = nums.length - 1;
while(l < h){
int j = partition(nums, l, h);
if(j == k)
break;
else if(j < k)
l = j + 1;
else
h = j - 1;
}
return nums[k];
}
private int partition(int[] a, int l, int h){
int i = l, j = h + 1;
while(true){
while(a[++i] < a[l] && i < h);
while(a[--j] > a[l] && j > l);
if(i >= j)
break;
swap(a, i, j);
}
swap(a, l, j);
return j;
}
private void swap(int[] a, int i, int j){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
python代码
from random import randint
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
if k > len(nums):
return
index = randint(0, len(nums)-1)
key = nums[index]
less_part = [i for i in nums[:index] + nums[index+1:] if i < key]
great_part = [i for i in nums[:index] + nums[index+1:] if i >= key]
if len(great_part) == k - 1:
return key
elif len(great_part) > k - 1:
return self.findKthLargest(great_part, k)
else:
return self.findKthLargest(less_part, k-len(great_part)-1)