Sunday, May 24, 2015

[LeetCode] 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 select:
class Solution {
public:
    int partition(vector<int>& nums, int start, int end, int k)
    {
        int pivot = nums[k];
        swap(nums[end], nums[k]);
        int storedIndex = start;
        for(int i=start;i<=end-1;i++)
        {
            if(nums[i]>pivot)
            {
                swap(nums[i], nums[storedIndex]);
                storedIndex ++;
            }
        }
        swap(nums[end], nums[storedIndex]);
        return storedIndex;
    }

    int findKthLargest(vector<int>& nums, int k) {
        int end = nums.size()-1;
        if(end<0) return 0;
        int start = 0;
        k--;
        int ret = partition(nums, start, end, k);
        while(k != ret)
        {
            if(ret < k) ret = partition(nums, ret+1, end, k);
            else ret = partition(nums, start, ret-1, k);
        }
        return nums[k];
    }
};