【LeetCode从零单刷】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 Sorting),每次将大于 key 的部分与小于 key 的部分区分出来。

如果小于 key 的个数大于 K,则不再寻找大于 key 的部分;如果小于 key 的个数小于 K,则寻找大于 key 的数中第(K - 小于 K 个数)大的数。

这样,每次大约有一半数字不需要寻找,时间复杂度约为O(n + n/2 + n/4 + .. + 1)= O(2n)= O(n).

最后,需要注意:快速排序、二分排序这一类,二分(递归)的子问题中应该去除中间元素(每次缩小范围,防止范围不变而死循环)。

class Solution {
public:
    void swap(int& a, int&b) {
        int tmp = a;
        a = b;
        b = tmp;
    }
    
    int findKthLargest(vector<int>& nums, int k) {
        int head = 0;
        int tail = nums.size() - 1;
        int index = 0;
        
        while(head < tail) {
            while(nums[tail] <= nums[index] && head < tail) tail--;
            swap(nums[tail], nums[index]);
            index = tail;
            
            while(nums[head] >= nums[index] && head < tail) head++;
            swap(nums[head], nums[index]);
            index = head;
        }
        
        if(k == index + 1)  return nums[index];
        else if(k < index + 1) {
            vector<int> sub(nums.begin(), nums.begin() + index);
            return findKthLargest(sub, k);
        }
        else if(k > index + 1) {
            vector<int> sub(nums.begin() + index + 1, nums.end());
            return findKthLargest(sub, k - index - 1);
        }
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值