Leetcode 215. Kth Largest Element in an Array
题目描述
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
输入:一个数组及序数k
输出:数组中第K大的数
思路
利用数据结构堆,将数组压入堆中,并进行k次出堆操作。时间复杂度
代码
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> pq;
if(nums.size()==0) return 0;
for(int i =0;i<nums.size();i++){
pq.push(nums[i]);
}
for(int i =1;i<k;i++){
if(pq.size()!=0)
pq.pop();
}
return pq.top();
}
};
本文介绍如何使用堆数据结构解决LeetCode 215题:寻找未排序数组中的第K大元素。通过实例讲解了算法思路,并提供了一段C++实现代码。
854

被折叠的 条评论
为什么被折叠?



