【LeetCode 215】Kth Largest Element in an Array

题目描述

在一个无序数组中找出第k大的元素。

思路

方法一: 排序,取第k个,O(nlogn)
方法二: 最小堆,维护最大k个元素的最小堆,堆顶元素不断和数组中剩余元素比较,如果堆顶元素小于数组元素,替换堆顶,并维护堆。O(n
logk)
方法三: 在快排过程中,不断返回标杆的位置,如果左边区间元素个数>k,那么在左区间继续寻找,否则在右区间寻找 (k-左区间元素个数)。时间复杂度接近 O(n)

代码

方法二:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int>> pq;
        int n = nums.size();
        int cnt = 0;
        for (; cnt<k; ++cnt) pq.push(nums[cnt]);
        
        while(cnt < n) {
            if (nums[cnt] < pq.top()) {
                cnt++;
                continue;
            }
            pq.pop();
            pq.push(nums[cnt]);
            cnt++;
        }
        return pq.top();
    }
};

方法三:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        return findKth(nums, 0, n-1, k);
    }
    
    int partitions(vector<int>& nums, int l, int r) {
        int key = nums[l];
        int i = l;
        int j = r;
        
        while(i < j) {
            while(i < j && nums[j] < key) j--;
            if (i < j) nums[i++] = nums[j];
            while(i < j && nums[i] >= key) i++;
            if (i < j) nums[j--] = nums[i];
        }
        nums[i] = key;
        return i;
    }
    
    int findKth(vector<int>& nums, int l, int r, int k) {
        if (l == r) return nums[l];
        int p = partitions(nums, l, r);
        cout << p << endl;
        int cnt = p - l + 1;
        if (cnt == k) {
            return nums[p];
        }else if (cnt > k) {
            return findKth(nums, l, p-1, k);
        }else {
            return findKth(nums, p+1, r, k-cnt);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值