215. Kth Largest Element in an Array (Medium)

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.

Soltuion 1: QuickSort 12ms

class Solution {
    int partition(vector<int>& nums, int lo, int hi) {
        int pivot = nums[hi];
        int i = lo;
        for (int j = lo; j < hi; ++j) {
            if (nums[j] > pivot) {
                swap(nums[i++], nums[j]);
            }
        }
        swap(nums[i], nums[hi]);
        return i;
    }

public:
    int findKthLargest(vector<int>& nums, int k) {
        int lo = 0, hi = nums.size()-1;
        --k; // index of kth largest
        std::random_shuffle (nums.begin(), nums.end() );
        while (lo < hi) {
            int i = partition(nums, lo, hi);

            if (i < k) lo = i+1;
            else if (i > k) hi = i-1;
            else return nums[k];
        }
        return nums[k];
    }
};

Solution 2: Super Easy

public:
int findKthLargest(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    return nums[nums.size()-k];
}

results matching ""

    No results matching ""