面试经典题:TOP-K问题(附快排+堆排C++实现)

数组中的第K个最大元素 [TOP-k问题]

// 1、采用快选
class Solution {
public:
    int quick_sort(vector<int>& nums,int l,int r,int k){
        if(l>=r) return nums[k];
        int a = l-1, b = r+1; int x = nums[a+b>>1];
        while(a<b){
            do a++; while(nums[a] > x);
            do b--; while(nums[b] < x);
            if(a<b) swap(nums[a],nums[b]);
        }
        if(b<k) return quick_sort(nums, b+1, r, k);
        else return quick_sort(nums, l, b, k);
    }
    int findKthLargest(vector<int>& nums, int k) {
        return quick_sort(nums,0,nums.size()-1, k-1);
    }
};

// 2、采用堆排序
class Solution {
public:
    int size;
    vector<int> h;
    void down(int u){
        int t = u;
        if(u*2 <= size && h[u*2] < h[t]) t = 2*u;
        if(u*2+1 <= size && h[u*2+1] < h[t]) t = 2*u+1;
        if(t != u){
            swap(h[u], h[t]);
            down(t);
        }        
    }
    int findKthLargest(vector<int>& nums, int k) {
        size = k;
        h.resize(k+1);
        int j=0;
        for(int i=1;i<=k;i++) h[i] = nums[j++];
        for(int i=k/2;i;i--) down(i);
        for(;j<nums.size();j++){
            if(nums[j] < h[1]) continue;
            h[1] = nums[j]; down(1);
        }
        return h[1];
    }
};

posted @ 2022-04-05 16:31  SrtFrmGNU  阅读(48)  评论(0编辑  收藏  举报