<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p>

<p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p>

<p>Can you solve it without sorting?</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2
<strong>Output:</strong> 5
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4
<strong>Output:</strong> 4
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
#if 1   // max-heap
    int findKthLargest(vector<int>& nums, int k) {
        int n=nums.size(), i;
        priority_queue<int, vector<int>, less<int>> p_queue; // max-heap
        // pop if heap size > n-k+1
        for(i=0; i<n; i++)
        {
            p_queue.push(nums[i]);
            if(p_queue.size() > (n-k+1))
                p_queue.pop();
        }
        return p_queue.top();
    }
#else   // quick selection
    int findKthLargest(vector<int>& nums, int k) {
        //find pivot index is n-k
        int n = nums.size();
        int i=0, j=n-1, pivot_idx, target_idx=n-k;
        while(i <= j)
        {
            pivot_idx = quick_selection(nums, i, j);
            if(pivot_idx > target_idx)
                j = pivot_idx - 1;
            else if(pivot_idx < target_idx)
                i = pivot_idx + 1;
            else
                return nums[pivot_idx];
        }
        return 0;       
    }
    int quick_selection(vector<int>& nums, int begin, int end)
    {       
        int pivot=nums[end], i=begin-1, j;
        for(j=begin; j<end; j++)
        {
            if(nums[j] < pivot)
            {
                i++;
                if(i != j)
                    swap(nums[i], nums[j]);
            }
        }
        i++;
        if(i != j) //j==end
            swap(nums[i], nums[j]);
        return i;         
    }
#endif    
};
62800