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.

 

 

解题思路:

这很容易想到,可以对数组进行排序,然后直接取k个最大的数字。

这样的时间复杂度为O(nlogn)

而使用partition来进行分割,可以达到均摊时间O(n)的时间复杂度。

 

代码:

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

 

posted @ 2018-07-20 07:58  妖域大都督  阅读(100)  评论(0编辑  收藏  举报