leetcode 215 数组第k大

/*
 * @lc app=leetcode.cn id=215 lang=cpp
 *
 * [215] 数组中的第K个最大元素
 */

// @lc code=start
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        srand(time(0));
        int n = nums.size();
        int x = nums[0];
        int ans = quickSelect(nums,0,n-1,n-k);
        return ans;
    }
    //在[l,r]中找到第index小的数
    int quickSelect(vector<int> &nums,int l,int r,int index) {

        rand_pos(nums,l,r);
        int pos = partition(nums,l,r);
        if(pos == index) {
            return nums[pos];
        }
        if(pos > index) {
            return quickSelect(nums,l,pos-1,index);
        }
        else if(pos < index){
            return quickSelect(nums,pos+1,r,index);
        }
        return 0;
    }
    //找到l-r里的一个随机元素,并和nums[r]替换
    //返回大于nums[r]的元素下标
    int rand_pos(vector<int> &nums,int l,int r) {
        int len = r-l+1;
        int rand_pos = l + (rand() % (len));
        swap(nums[rand_pos],nums[r]);
        return 0;
    }
    //把[l,r]里面小于nums[r]的元素放在前面
    //返回大于nums[r]的元素下标
    int partition(vector<int> &nums,int l,int r) {
        int x = nums[r];
        int j = l-1;
        for(int i=l;i<r;i++) {
            if(nums[i] <= x) {
                swap(nums[++j],nums[i]);
            }
        }
        swap(nums[j+1],nums[r]);
        return j+1;
    }
};
// @lc code=end
posted @ 2021-12-17 15:41  hh13579  阅读(19)  评论(0编辑  收藏  举报