【LeetCode】215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

Description:
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Difficulty:Medium

Example:

Input: [3,2,1,5,6,4] and k = 2
Output: 5
方法1:sort
  • Time complexity : O ( n l o g n ) O\left ( nlogn\right ) O(nlogn)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
class Solution {
public:
	int findKthLargest(vector<int>& nums, int k) {
		sort(nums.begin(), nums.end(), [](const int& a, const int& b) {return a > b; });
		return nums[k - 1];
	}
};
方法2:min-heap
  • Time complexity : O ( n l o g k ) O\left ( nlogk\right ) O(nlogk)
  • Space complexity : O ( k ) O\left ( k \right ) O(k)
    思路
    维护k大小的最小堆,到最后的top便是结果
class Solution {
public:
	int findKthLargest(vector<int>& nums, int k) {
		priority_queue<int, vector<int>, greater<int> > pq;
		for (auto num : nums) {
			pq.push(num);
			if (pq.size() > k)
				pq.pop();
		}
		return pq.top();
	}
};
方法3:Quick select
  • Time complexity : O ( n ) O\left ( n\right ) O(n)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
    思路
    利用快排中的partition,比快排要少一半的操作,因为每次左右两边的递归只运行一个即可。
class Solution {
public:
	int findKthLargest(vector<int>& nums, int k) {
        int left = 0, right = nums.size() - 1;
        while (true) {
            int p = partition(nums, left, right);
            if (p == k - 1) {
                return nums[p];
            }
            if (p > k - 1) {
                right = p - 1;
            } else {
                left = p + 1;
            }
        }
    }
    
    int partition(vector<int>& nums, int left, int right){
        int pivot = nums[left], l = left+1, r = right;
        while(true){
            while(l <= right && nums[l] > pivot) l++;
            while(left+1 <= r && nums[r] < pivot) r--;       
            if(l > r) break;
            swap(nums[l++], nums[r--]);
            }
        swap(nums[left], nums[r]);
        return r;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值