LintCode(5)-第k大元素

在数组中找到第 k 大的元素。ps:使用快排

class Solution {
public:
    /**
     * @param k: An integer
     * @param nums: An array
     * @return: the Kth largest element
     */
    int kthLargestElement(int k, vector<int> &nums) {
        // write your code here
        int n = nums.size();
        return partition(nums, 0, n-1, k);
    }
    int partition(vector<int>& nums, int start, int end, int k) {
        int left = start, right = end;
        int pivot = nums[left];
        
        while (left <= right) {
            while (left <= right and nums[left] > pivot) {
                left++;
            }
            while (left <= right and nums[right] < pivot) {
                right--;
            }
            if (left <= right) {
                swap(nums[left], nums[right]);
                left++;
                right--;
            }
        }
        if ((k-1) <= right) {
            return partition(nums, start, right, k);
        }
        if ((k-1) >= left) {
            return partition(nums, left, end, k);
        }
        return nums[k-1];
    }
};

猜你喜欢

转载自blog.csdn.net/Qmingwt/article/details/125921055