题解 | #寻找第K大#

寻找第K大

http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf

快速排序+从打到小

class Solution {
public:
    int findKth(vector<int> a, int n, int K) {
        // write code here

        return QuickSort(a, 0, n - 1, K);
    }


    int QuickSort(vector<int> a, int start, int end, int k)
    {
        int pivot = a[start];
        int low = start;
        int high = end;
        int res = 0;

        while(low < high)
        {
            while(low < high && a[high] <= pivot)
                high--;
            a[low] = a[high];
            while(low < high && a[low] >= pivot)
                low++;
            a[high] = a[low];
        }
        a[low] = pivot;

        if(low + 1 == k)
            return a[low];
        else if(low + 1 > k)
            res = QuickSort(a, start, low - 1, k);
        else
            res = QuickSort(a, low + 1, end, k);

        return res;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务