215. Kth Largest Element in an Array(partition逆序排序,index+1 == k)

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

 
class Solution {
public:
    /**
     * @param n: An integer
     * @param nums: An array
     * @return: the Kth largest element
     */
    //第k大的数用快排: 4 5 3 2 5
    int partition(vector<int>& nums,int left,int right) {
        int pivot = nums[right], k=left;
        if(left < right){
            for(int i=left;i<right;i++){
                //逆序
                if(nums[i] >= pivot){
                    swap(nums[k++],nums[i]);
                }
            }
            swap(nums[k],nums[right]);
            return k;
        }
    }
    int search(vector<int> &nums,int n,int left,int right) {
        int index = partition(nums,left,right);
        if(index+1-left == n) return nums[index];
        else if(index+1-left > n) return search(nums,n,left,index-1);
     //右半部分:只找n-(index+1-left)个元素
else return search(nums,n-(index+1-left),index+1,right); } int kthLargestElement(int n, vector<int> &nums) { int left =0,right=nums.size()-1; return search(nums,n,left,right); } };

 

class Solution {
public:
    //关键 逆序partition,从大到小  3 2 1 5 6 4 
    int partition(vector<int>& nums,int left,int right) {
        int pivot = nums[right],k = left;
        if(left < right){
            for(int i=left;i < right;i++){
                if(nums[i] >= pivot){
                    swap(nums[i],nums[k++]);
                }
            }
            //只能到right-1,否则k有问题。
            swap(nums[k],nums[right]);
        }
        return k;
    }
    
    int Search(vector<int>& nums,int k) {
        int left = 0,right = nums.size()-1;
        int index = partition(nums,left,right);
        if(index+1 == k) return nums[index];
        while(index+1 != k){
            //第k大的数在右半边
            if(index+1 < k){
                left = index+1;
                index = partition(nums,left,right);
            }else{
                right = index -1;
                index = partition(nums,left,right);
            }
        }
        return nums[index];
    }
    
    int findKthLargest(vector<int>& nums, int k) {
        return Search(nums,k);
    }
};

 

posted on 2020-12-06 15:06  wsw_seu  阅读(117)  评论(0编辑  收藏  举报

导航