[leetcode] Kth Largest Element in an Array


Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Quick sort, find the k-th largest number.

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        return quickSort(nums, 0, nums.size() - 1, k);
    }
    int quickSort(vector<int>& nums, int start, int end, int k){
        int pivot = nums[end];
        int low = start;
        int high = end - 1;
        while(low <= high){
            if(nums[low] > pivot){
                swap(nums[low], nums[high]);
                high--;
            }else{
                low++;
            }
        }
        swap(nums[low], nums[end]);
        int rank = nums.size() - k;
        if(low == rank) return nums[low];
        else if(low < rank){
            return quickSort(nums, low + 1, end, k);
        }else{
            return quickSort(nums, start, low - 1, k);
        }
    }
};

 

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.