One Code 215 a day. The Kth largest element in an array

insert image description here

The simplest code idea is to sort it once and then output it directly. The time complexity is the complexity of sorting O ( nlogn ) O(nlogn)O ( n l o g n )

Optimization is to use the idea of ​​quick sort, not to sort all, but to return directly when the found position is exactly the required position, otherwise, continue to sort the left or right by judging the size of K and the current position. The worst-case time complexity of this idea is equal to O(nlogn) O(nlogn) for direct sorting outputO ( n l o g n ) . emmm The average time complexity will not prove, or it is too troublesome to think about.

Code:

class Solution {
    
    
public:
    int quicksort(vector<int> &a,int l,int r,int k){
    
    
        //递归解决问题
        if(l == r) return a[l];
        int i = l,j = r,base = a[l];
        while(i != j){
    
                                  //快排思想
            while(i < j && a[j] >= base) j--;       //左边基准,右边先搜
            while(i < j && a[i] <= base) i++;
            if(i<j) swap(a[i],a[j]);
        }
        swap(a[i],a[l]);
        if(i == k) return a[k];                     //找到后直接返回
        else if(i > k) return quicksort(a,l,i-1,k); //向两边找
        else return quicksort(a,i+1,r,k);
    }
    int findKthLargest(vector<int>& nums, int k) {
    
    
        //寻找第k大
        return quicksort(nums,0,nums.size()-1,nums.size()-k);
    }
};

Guess you like

Origin blog.csdn.net/qq_41746268/article/details/108224867