Leetcode 215. 数组中的第K个最大元素

题目

在这里插入图片描述
Leetcode 215. 数组中的第K个最大元素

代码(8.22 首刷自解)

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int> q;
        for(int& i : nums) {
            q.push(i);
        }
        for(int i = 0; i < k-1; i++) {
            q.pop();
        }
        return q.top();
    }
};

Quick Select 快速选择排序

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        return quickSort(nums, 0, n-1, n-k);
    }
    int quickSort(vector<int>& nums, int start, int end, int target) {
        if(start == end)
            return nums[target];
        int pivot = nums[rand()%(end-start+1)+start];
        int i = start-1, j = end+1;
        while(i < j) {
            while(nums[++i] < pivot);
            while(nums[--j] > pivot);
            if(i < j) swap(nums[i], nums[j]);
        }
        if(j >= target) return quickSort(nums, start, j, target);
        return quickSort(nums, j+1, end, target);
    }
};

代码(9.4 二刷自解)

手撕大根堆

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        buildHeap(nums);
        int n = nums.size()-1;
        for(int i = 0; i < k-1; i++) {
            swap(nums[0], nums[n-i]);
            heapAdjust(nums, 0, n-i-1);
        }
        return nums[0];
    }
    void buildHeap(vector<int>& nums) {
        int n = nums.size()-1;
        for(int i = (n-1)/2; i >= 0; i--) {
            heapAdjust(nums, i, n);
        }
    }
    void heapAdjust(vector<int>& nums, int k, int n) {
        for(int i = 2*k+1; i <= n; i = i*2+1) {
            if(i+1 <= n && nums[i+1] > nums[i]) {
                i++;
            }
            if(nums[k] < nums[i]) {
                swap(nums[k], nums[i]);
                k = i;
            } else {
                return;
            }
        }
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值