215. Kth Largest Element in an Array
阿新 • • 發佈:2021-01-19
技術標籤:LeetCode
題目:
Find thekth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4]
and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
思路:
老且經典的題了,topK問題。比較一般的思路是可以先陣列先sort,然後返回對應index的值即可,但是面試肯定不夠,這裡講一下複雜度為的方法:藉助最大堆。因為我們需要k個最大值,因此用最大堆來維護這k個值:遍歷陣列,講當前值往堆裡塞,然後判斷,如果堆的size已經大於k了,那麼第k+1大的數字我們是不用的,而因為是最大堆,堆尾是當前k+1個數中的最小值,直接pop出來即可。最後是當前的k個最大值,堆頂是這k箇中的最大值,直接返回堆頂即可。
程式碼:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
for(int i=0;i<nums.size();i++)
{
temp.push(nums[i]);
if(temp.size()>k)
temp.pop();
}
return temp.top();
}
};