首页 > 其他 > 详细

Kth Largest Element in an Array -- leetcode

时间:2015-08-20 18:55:26      阅读:151      评论:0      收藏:0      [点我收藏+]

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.



基本思路:

用快排的划分。

选定一个pivot,作一次划分,就能确定pivot的实际位置。

然后以此位置和目标位置作比较。逐步缩小范围。

下面划分的代码,是模仿严蔚敏演示的步骤。比较易懂易记。

既,

1.先取左端点作pivot,取出值后,该位置可视为待填充位置。

2. 在右边寻求第一个不满足条件的点,即大于pivot的值。 将该值赋于步骤1所得到的空闲位置处。 则此位置成为新的待填充位置。

3. 再从左边寻找第一个不满足条件的点,即小于pivot的值。将该值赋于步骤2所得的空间位置处。

重复步骤2和3.


class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        --k;
        int start = 0, stop = nums.size()-1;
        while (start < stop) {
            int pivot = nums[start];
            int i = start, j = stop;
            while (i < j) {
                while (i < j && nums[j] <= pivot) --j;
                if (i == j) break;
                nums[i] = nums[j];
                ++i;
                while (i < j && nums[i] >= pivot) ++i;
                if (i == j) break;
                nums[j] = nums[i];
                --j;
            }
            nums[i] = pivot;
            if (i == k) 
                return pivot;
            else if (k < i)
                stop = i-1;
            else
                start = i+1;
        }
        return nums[start];
    }
};


将划分的代码略改进一下:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        --k;
        int start = 0, stop = nums.size()-1;
        while (start < stop) {
            int pivot = nums[start];
            int i = start, j = stop;
            while (i <= j) {
                while (i<=j && nums[j] < pivot) --j;
                while (i<=j && nums[i] >= pivot) ++i;
                if (i<j)
                    swap(nums[i], nums[j]);
            }
            swap(nums[start], nums[j]);
            i = j;
            if (i == k) 
                return pivot;
            else if (k < i)
                stop = i-1;
            else
                start = i+1;
        }
        return nums[start];
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

Kth Largest Element in an Array -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/47811575

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!