[leetcode] 215. Kth Largest Element in an Array

    xiaoxiao2026-04-05  8

    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.

    解法一:

    所以如果用vector的built-in函数,这题没啥意思。

    class Solution { public: int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(),nums.end()); return nums[nums.size()-k]; } };

    解法二:

    还有用std::priority_queue的解法,这里queue有个top()函数,神奇。

    class Solution { public: int findKthLargest(vector<int>& nums, int k) { priority_queue<int, vector<int>, greater<int>> q; for(auto &a:nums){ q.push(a); if(q.size()>k) q.pop(); } return q.top(); } };

    转载请注明原文地址: https://ju.6miu.com/read-1308512.html
    最新回复(0)