寻找第K大

来源:互联网 发布:linux中文输入法切换 编辑:程序博客网 时间:2024/04/27 21:12

有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。

给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。

测试样例:
[1,3,5,2,2],5,3
返回:2
class Finder {public:    int partition(vector<int>& a,int low,int high)    {        int povit=a[low];        while(low<high)        {            while(low<high&&povit<=a[high])                high--;            a[low]=a[high];            while(low<high&&povit>=a[low])                low++;            a[high]=a[low];        }        a[low]=povit;        return low;    }    int findKth(vector<int> a, int n, int K) {        // write code here        int len=a.size();        if(len!=n||n==0||n<K) return 0;                int index=partition(a,0,n-1);        //if(index==n-K) return a[index];                while(index!=n-K)        {            if(index>n-K)               index=partition(a,0,index-1);            else               index=partition(a,index+1,n-1);        }                return a[index];    }};







0 0
原创粉丝点击