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

来源:互联网 发布:长波电台事件 知乎 编辑:程序博客网 时间:2024/06/04 04:17

题目链接: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 partition(vector<int>& nums, int left, int right)    {        int val = nums[right];        for(int i = left; i < right; i++)            if(nums[i] < val) swap(nums[left++], nums[i]);        swap(nums[right], nums[left]);        return left;    }        int findKthLargest(vector<int>& nums, int k) {        int len = nums.size(), left = 0, right = len-1, ans, pos = len-k;        while((ans=partition(nums, left, right)) != pos)            ans<pos?left = ans + 1: right = ans - 1;        return nums[len-k];    }};




0 0