LeetCode|Kth Largest Element in an Array

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.

思路均来自《编程之美》
方法一:
选择排序找出前k个最大的,复杂度O(n*k)

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        for(int i = 0; i < k; i++){ // O(n*k)
            int maxId = i;
            for(int j = i+1; j < n; j++){
                if(nums[j] > nums[maxId]) maxId = j;
            }
            swap(nums[i], nums[maxId]);
        }
        return nums[k-1];
    }
};

方法二:
O( n log n )排序之后输出第k大的,和方法一的复杂度比较要看K和log n 谁大谁小

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        sort(nums.rbegin(), nums.rend());
        return nums[k-1];
    }
};

方法三:
利用快速排序partition的思想,每次把不小于pivot的数放左边,小于pivot的数放右边。最后判断一下pivot的下标与k-1的关系,然后返回pivot或者缩小范围继续递归。时间复杂度为O( n log k)? 好像是O(n)

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        return helper(nums, 0, nums.size()-1, k);
    }
private:
    int helper(vector<int>& nums, int s, int e, int k){
        int lastLarge = s; // pivot is nums[s]
        for(int i = s+1; i <= e; i++){
            if(nums[i] >= nums[s])
                swap(nums[++lastLarge], nums[i]);
        } swap( nums[s], nums[lastLarge]);
        if(lastLarge == k-1) return nums[lastLarge];
        if(lastLarge < k) return helper(nums, lastLarge+1, e, k); // lastLarge < k-1
        return helper(nums, s, lastLarge-1, k); // lastLarge >= k
    }
};

方法四:
条件允许可以改为桶排序,本题输入的数据范围不明确所以不能使用。n个正整数范围[0, MAXN-1], count[i]用来代表 i出现了count[i]次

for(sumCount = 0, i = MAXN-1; i>= 0; i--){
	sumCount += count[i];
	if(sumCount >= k) return i;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值