寻找数组中第K大元素CPP实现

 简单实现:

运用STL秒实现!

class Solution {
public:
    int findKth(vector<int> a, int n, int K) {
        // write code here
        sort(a.begin(), a.end());
        return a[n-K];
    }
};

完事!~~~   当然还可以优化一下!

优化实现:

快排 + 二分法

鉴于快速排序的特点,每一次排序,都会找到一个基准值,左面放比他小的,右面放比它大的,但是快排会对全部数据进行排序(递归,左面和右面),如果重写快排的逻辑,使数据按从大到小的顺序排列,在一次排序后加一次判断:如果基准左面的值个数恰好为k-1个,则基准值就为第K大值;如果左面的值个数小于K-1个,则第K大值不在左面,直接放弃左面的排序,进行右面的排序。

 

class Solution {
public:
    int findKth(vector<int> a, int n, int K) {
        // write code here
        return SortToFindK(a, 0 , n - 1, K);
    }
    
    /** 重写核心逻辑,使排序规则为大数在左,并且只执行一次排序,没有递归逻辑*/
    int MySort(vector<int> &a,int low, int hight)
    {
        int temp = a[low];
        while(low < hight)
        {
           while(low < hight && a[hight] <= temp) hight--;
           if(low == hight) break;
           else a[low] = a[hight];
           while(low < hight && a[low] >= temp) low++;
           if(low == hight) break;
           else a[hight] = a[low];
        }
        a[low] = temp;
        return low;
    }
    
    /**排序筛选逻辑*/
    int SortToFindK(vector<int> &a,int low, int hight,int K)
    {
        /**进行一轮排序,接收基准值位置下标*/
        int Key = MySort(a,low,hight);
        if(K == Key -low + 1 ) return a[K]; //如果刚好为K+1位置,则找到
        else if(Key -low + 1 > K) return SortToFindK(a,low,Key-1,K);
        else return SortToFindK(a,Key + 1,hight, K - Key + low - 1 );
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lxy_lucky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值