[leetcode] 215. Kth Largest Element in an Array 解题报告

题目链接:https://leetcode.com/problems/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.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

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



思路:这题是利用了quick-select的算法,也就是快速排序的partition,这个方法的理论时间复杂度是O(n),是一种非常有用的工具.

使用分治每次将数组划分为两段,并且返回划分点的位置,如果这个位置恰好是我们要的第k大的数,那么返回这个数即可,

否则如果返回的位置小于要找的位置,则向右边的一半数组继续寻找

如果返回的位置大于要找的位置,则向左边寻找.

代码如下:

class Solution {
public:
    int findKth(vector<int>& nums, int low, int high)
    {
        int val = nums[high], k = low-1;
        for(int i = low; i< nums.size(); i++)
            if(nums[i] < val) 
                swap(nums[++k], nums[i]);
        swap(nums[high], nums[++k]);
        return k;
    }
    int findKthLargest(vector<int>& nums, int k) {
        int len = nums.size(), low = 0, high = len-1, pos=-1;
        while(low <= high)
        {
            pos = findKth(nums, low, high);
            if(pos == len-k) return nums[pos];
            else if(pos > len-k) high = pos-1;
            else if(pos < len-k) low = pos+1;
        }
    }
};


你可能感兴趣的:(LeetCode,分治)