【快排patition思想】215. 数组中的第K个最大元素

主要是partition函数的书写,其中两个while循环的顺序改变了会出错。

class Solution {
public:
    int patition(vector<int>& nums, int left, int right){
        int i = left, j = right;
        int temp = nums[i];
        while(i < j){
            while(i < j && nums[j] >= temp) j--;      // 两个while循环的顺序不能变
            while(i < j && nums[i] <= temp) i++;
            swap(nums[i], nums[j]);
        }
        swap(nums[left], nums[j]);
        return j;
    }

    int findKthLargest(vector<int>& nums, int k) {
        int left = 0, right = nums.size() -1;
        k = nums.size() - k;
        while(true){
            int p = patition(nums, left, right);
            // cout << p << endl;
            // for (auto a: nums){
            //     cout << a <<" ";
            // }
            // cout << endl;
            if(p == k)
                return nums[p];
            else if(p > k){
                right = p - 1;
            }
            else
                left = p + 1;
        }
    }
};


posted @ 2022-02-28 19:58  fwx  阅读(37)  评论(0)    收藏  举报