Leetcode215. Kth Largest Element in an Array

这是一道分治的题目,去面网易的机器学习岗位的时候问了我这个问题,我那时候第一反应就是桶排序。。

先附上桶排序的代码如下,应该注意两个地方:1、排序的数有可能是负数;2、排序的数有可能是重复的,比如[99 99],要找出第一大的数,这种情况对于判断第几大的时候要采用大于等于而不是直接用等于来判断。

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int array[20000];
        int i;
        for(i = 0; i < 20000; i++){
            array[i] = 0;
        }
        for(i = 0; i < nums.size(); i++){
            array[nums[i]+10000]++;
        }
        int count = 0;
        for(i = 19999; i >= 0; i--){
            if(array[i] >= 1){
                count = count + array[i];
            }
            if(count >= k)
                break;
        }
        return i-10000;
    }
};

接下来用分治的思想,跟快排差不多的思想,代码如下:

class Solution {
public:
    int partition(vector<int>& nums, int low, int high){
        int pivot = nums[low];
        while(low < high){
            while(low < high && nums[high] <= pivot) high--;
            nums[low] = nums[high];
            while(low < high && nums[low] >= pivot) low++;
            nums[high] = nums[low];
        }
        nums[low] = pivot;
        return low;
    }
    int findKthLargest(vector<int>& nums, int k) {
        int start = 0;
        int end = nums.size()-1;
        k--;
        while(1){
            int pivot = partition(nums, start, end);
            if (pivot == k){
                return nums[pivot];
            }
            else if(pivot < k){
                start = pivot+1;
            }
            else
                end = pivot-1;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值