1. 程式人生 > >Kth largest element in an array -- LeetCode 215

Kth largest element in an array -- LeetCode 215

很明顯快排,但快得不是很明顯

int findKthLargest(vector<int>& nums, int k) {
    
    return quickSort(nums,0,nums.size() - 1,k);
}

int quickSort(vector<int>& nums,int left,int right,int k)
{
    
    if(k > right + 1) return 0;         //若 k 比nums.size()還大,就return 0
    
    int pivot = left;
    
    int temp = partition(nums,left,right);
    swap(nums,temp,pivot);
        
    if(temp == k - 1)
        return nums[temp];
    else if(k - 1 < temp)
        return quickSort(nums,left,temp-1,k);
    else
        return quickSort(nums,temp + 1,right,k);
}

int partition(vector<int>& nums,int left,int right) {
    
    int temp = nums[left];
    while(left < right)
    {
        while(nums[right] < temp) right--;
        
        while(left < right && nums[left] >= temp) left++;
       
        swap(nums,left,right);
    }
    return left;
}

void swap(vector<int>& nums,int left,int right)
{
    int a = nums[left];
    nums[left] = nums[right];
    nums[right] = a;
}