5. 第k大元素【中等】

在数组中找到第k大的元素。

思路:快排,然后直接输出。

我的代码是直接用了STL的函数sort:

class Solution
{
    public:
        /*
         * @param n: An integer
         * @param nums: An array
         * @return: the Kth largest element
         */

        int kthLargestElement(int n, vector<int> &nums)
        {
            // write your code here
            sort(nums.begin(),nums.end());
            return nums[nums.size()-n];
        }
};

但标准答案是手写一个快速排序:

class Solution {
public:
    /*
     * param k : description of k
     * param nums : description of array and index 0 ~ n-1
     * return: description of return
     */
    int kthLargestElement(int k, vector<int> nums){
        return helper(nums, 0, nums.size() - 1, nums.size() - k + 1);
    }
    
    int helper(vector<int> &nums, int left, int right, int k) {
        if (left == right) {
            return nums[left];
        }
        
        int i = left, j = right;
        int pivot = nums[(i + j) / 2];
        while (i <= j) {
            while (i <= j && nums[i] < pivot) {
                i++;
            }
            while (i <= j && nums[j] > pivot) {
                j--;
            }
            if (i <= j) {
                swap(nums[i], nums[j]);
                i++;
                j--;
            }
        }


        if (left + k - 1 <= j) {
            return helper(nums, left, j, k);
        }
        
        if (left + k - 1 < i) {
            return nums[left + k - 1];
        }

        return helper(nums, i, right, k - (i - left));
    }
};

 备注:后来自己也试着手动写了一个快排,然后出了各种错误。。。比如没考虑到元素全部相同导致死循环,没有剪枝优化之类的。。。改了一天还是卡在77%的数据,从TLE改到WA。。。决定先放着,以后再想。

posted @ 2018-01-25 10:29  陈阿毛  阅读(98)  评论(0)    收藏  举报