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

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

解题思路:

这道题我一开始觉得最优也是要NlogN的时间复杂度,因为是无序的,我们需要对他进行排序,无论用堆还是什么其他的排序算法,应该都是要nlogn的。

后来就排序取了返回值,看了一下别人的做法,还是我太naive了。。

这里可以用快速排序的思想:Divide and Conquer

对于pivot值,我们找到pivot在数组中应该放置的地方:

  所有下标小于pivot最后位置的值都应该小于pivot,所有下标大于pivot最后位置的值都应该大于pivot。

这个时候我们可以观察pivot的位置,来确定接下来对那一部分进行细分,直到pivot的最终位置是nums.size()-K;

代码:

// quick select
class Solution {
public:
    int findKthLargest(vector<int> &nums, int k)
    {
        int n = nums.size();
        if (k <= 0 || n < k)
            return INT_MIN;
        
        return quick_select(nums, 0, n-1, n-k+1);
    }
    
    // quick select the k-th smallest element in the range [l, r]
    int quick_select(vector<int> &nums, int l, int r, int k)
    {
        if (l > r)
            return INT_MIN;
        
        int index = rand() % (r-l+1) + l;
        std::swap(nums[l], nums[index]);
        
        int i = l;
        for (int j = l; j <= r; ++j)
            if (nums[j] < nums[l])
                std::swap(nums[++i], nums[j]);
        std::swap(nums[l], nums[i]);
        
        if (i-l+1 == k)
            return nums[i];
        else if (i-l+1 > k)
            return quick_select(nums, l, i-1, k);
        else
            return quick_select(nums, i+1, r, k-(i-l+1));
    }
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/11711285.html