题目:
代码(2023年10月27日首刷看解析):
class Solution {
public:int findKthLargest(vector<int>& nums, int k) {return quickselect(nums,k);}int quickselect(vector<int>& nums,int k){vector<int> big,equel,small;int pivot = nums[rand()%nums.size()];for(auto num:nums){if(num>pivot){big.push_back(num);}else if(num<pivot){small.push_back(num);}else{equel.push_back(num);}}if(k<=big.size()){return quickselect(big,k);}else if(nums.size()-small.size()<k){return quickselect(small,k-(nums.size()-small.size()));}return pivot;}
};
时间复杂度为O(N)