题目:

//方法一,利用优先队列小顶堆greater(大顶堆是less)
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int>> q;
        for(auto n:nums){
            q.push(n);
            if(q.size()>k) q.pop();
        }
        return q.top();
    }
};
//方法二,分治快排
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        return traversal(nums, k);
    }
    int traversal(vector<int>& nums, int k){
        int base = nums[rand()%nums.size()];
        vector<int> small, equall, big;
        for(int n:nums){
            if(n>base){
                big.emplace_back(n);
            }else if(n<base){
                small.emplace_back(n);
            }else{
                equall.emplace_back(n);
            }
        }
        if(k<=big.size()) return traversal(big, k);
        else if(big.size()+equall.size()<k) return traversal(small, k-(big.size()+equall.size()));
        else return base;
    }
};
posted on 2024-03-10 21:25  孜孜不倦fly  阅读(8)  评论(0编辑  收藏  举报