215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

Find the k th largest element in an unsorted array. Note that it is the k th 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.

分析:
寻找第k大的数字,最朴素的想法就是我先把数组排好序,然后直接取第k大的数字就行了。可是排序最快也需要O(nlog(n))的时间复杂度,并且部门并不需要所有的数字都排好序。因此,我们可以借鉴快排的思想去解决这道题。

  1. 取第一个元素作为pivot,与后面的数字进行比较。
  2. 如果遇到比pivot小的数字,就将该数字放到pivot的右边,如果比pivot大的数字, 就放在pivot左边。
  3. 重复过程(2)
  4. 对比pivot的下标和k值,如果等于k值,则找到第k大的数字,如果小于k值,则在pivot的右边找第k - l.length()大的数字,如果大于k值,则在pivot的左边找第k大的数字。

代码:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int start = 0, end = nums.size() - 1;
        while (true) {
            int largeIndex = findKthLargestRec(nums, start, end);
            if (largeIndex == k - 1) return nums[largeIndex];
            if (largeIndex > k - 1) end = largeIndex - 1;
            else start = largeIndex + 1;
        }
    }

    int findKthLargestRec(vector<int>& nums, int start, int end) {
        int pivot = nums[start];
        int s = start + 1, e = end;
        while (s <= e) {
            if (nums[s] < pivot && nums[e] > pivot)
                swap(nums[s++], nums[e--]);
            if (nums[s] >= pivot) s++;
            if (nums[e] <= pivot) e--;
        }
        swap(nums[start], nums[e]);
        return e;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值