class Solution { public: int quicksort(vector<int>& nums, int start, int end, int k){ int i = start; int j = end; int x = nums[i]; while (i<j){ //快排核心… while (nums[j]<x && i<j) j--; if (i<j) nums[i++] = nums[j]; while (nums[i]>x && i<j) i++; if (i<j) nums[j--]=nums[i]; } nums[i] = x; if (i==k-1) return x; else if (i>k-1) //出错的地方…………………… return quicksort(nums,start,i-1,k); else return quicksort(nums,i+1,end,k); } public: int findKthLargest(vector<int>& nums, int k) { int len = nums.size(); //思路:快排,从大到小,放在第(K-1)处的就是第k大的 int res = quicksort(nums,0,len-1,k); return res; } };
原文地址:https://www.cnblogs.com/sherry-yang/p/8282650.html
时间: 2024-10-30 08:46:45