215 数组中的第K个最大元素

本文最后更新于:2021年1月14日 下午

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

1
2
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5

示例 2:

1
2
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4

说明:

你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

Solution

  • 利用标准库排序算法
1
2
3
4
5
6
7
8
9
// @lc code=start
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end(), greater<int>());
return nums[k-1];
}
};
// @lc code=end
  • 快速排序算法,参考**@liuyubobobo**
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
int quickSort(vector<int>& nums, int l, int r, int k){
if (l==r)
return nums[l];

int pivot = partition(nums, l, r);
if (pivot==k)
return nums[pivot];
else if (k<pivot)
return quickSort(nums, l, pivot-1, k);
else
return quickSort(nums, pivot+1, r, k);
}

int partition(vector<int>& nums, int l, int r){
int p = rand()%(r-l+1)+l;
swap(nums[p], nums[l]);
int lt = l+1;
for (int i = l+1; i <= r; ++i) {
if (nums[i]>nums[l])
swap(nums[i], nums[lt++]);
}
swap(nums[l], nums[lt-1]);
return lt-1;
}

int findKthLargest(vector<int>& nums, int k) {
return quickSort(nums, 0, nums.size()-1, k-1);
}
};
  • 堆排序算法,参考 @liuyubobobo
  • 维护一个 k 大小的小顶堆,堆顶就是第 k 大的数
  • 当堆大小为 k 时,还要与堆顶元素比较,判断新元素是否加入堆中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
for(int e: nums){
if(pq.size()!=k)
pq.push(e);
else if(e>pq.top()){
pq.pop();
pq.push(e);
}
}
return pq.top();
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!