Sunday, July 23, 2017

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.


Solution:
class Solution {
public:
    int partition(vector<int>& nums, int st, int end) {
        int pivot = nums[end];
        int i = st, iter = st;
        while (i < end) {
            if (nums[i] <= pivot) {
                iter_swap(nums.begin() + i, nums.begin() + iter);
                iter++;
            }
            i++;
        }
        iter_swap(nums.begin() + end, nums.begin() + iter);
        return iter;
    }
   
    int quickPK(vector<int>& nums, int st, int end, int k) {
        int p = partition(nums, st, end);
       
        if (p == k) {
            return nums[p];
        } else if (p > k) {
            return quickPK(nums, st, p - 1, k);
        } else {
            return quickPK(nums, p+1, end, k);
        }
    }
   
    int findKthLargest(vector<int>& nums, int k) {
        int size = nums.size();
        int end = nums.size() - 1, start = 0;
        return quickPK(nums, start, end, size - k);
    }
};

No comments:

Post a Comment