1. 程式人生 > >215. Kth Largest Element in an Array 第K大的數

215. Kth Largest Element in an Array 第K大的數

start ++ uic find sta 第k大 ret color post

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; } };

215. Kth Largest Element in an Array 第K大的數