Kth Largest Element in an Array -- leetcode

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];
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值