215. Kth Largest Element in an Array(图解)

215. Kth Largest Element in an Array

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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Solution

C++
Sol1:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int, vector<int>, greater<int> > pq;
        for(int n: nums) {
            pq.push(n);
            if(pq.size() > k) pq.pop();
        }
        return pq.top();
    }
};

Sol2:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        k = nums.size() - k;
        int l = 0, r = nums.size() - 1;
        while(l < r) {
            int pivotIndex = partition(nums,l,r);
            if(pivotIndex < k) l = pivotIndex + 1;
            else if(pivotIndex > k) r = pivotIndex - 1;
            else break;
        }
        return nums[k];
    }
    
    int partition(vector<int>& a, int left, int right) {
        int pivotIndex = left+(right-left)/2;
        int pivot = a[pivotIndex];
        swap(a[pivotIndex], a[right]);
        int l = left, r = right-1;
        while(l <= r) {
            if(a[l] < pivot) ++l;
            else if(a[r] >= pivot) --r;
            else {
                swap(a[l], a[r]);
                ++l;
                --r;
            }
        }
        swap(a[l], a[right]);
        return l;
    }
};

Explanation
Sol1: Min heap

Time: O ( n l o g k ) O(nlogk) O(nlogk)

在这里插入图片描述

Sol2: Partition

Time: average O ( N ) O(N) O(N) ,worst O ( N 2 ) O(N^2) O(N2)

In average, this algorithm reduces the size of the problem by approximately one half after each partition, giving the recurrence T(n) = T(n/2) + O(n) with O(n) being the time for partition. The solution is T(n) = O(n), which means we have found an average linear-time solution. However, in the worst case, the recurrence will become T(n) = T(n - 1) + O(n) and T(n) = O(n^2).

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值