<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:
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        std::vector<int> tmp(n);
        mergeSelect(nums, tmp, 0, n - 1, k);
        return nums[k - 1];
    }

    void mergeSelect(vector<int>& nums, vector<int>& tmp, int L, int R, int k) {
        if (R <= L) return;
        int mid = L + (R - L) / 2;
        mergeSelect(nums, tmp, L, mid, k);
        mergeSelect(nums, tmp, mid + 1, R, k);
        mergeK(nums, tmp, L, mid, mid + 1, R, k);
    }
    
    void mergeK(vector<int>& nums, vector<int>& tmp, int L1, int R1, int L2, int R2, int k) {
        int base = L1;
        int curr = L1;
        while (L1 <= R1 && L2 <= R2 && curr - base < k) {
            if (nums[L1] > nums[L2]) {
                tmp[curr++] = nums[L1++];
            } else {
                tmp[curr++] = nums[L2++];
            }
        }
        while (L1 <= R1 && curr - base < k) {
            tmp[curr++] = nums[L1++];
        }
        while (L2 <= R2 && curr - base < k) {
            tmp[curr++] = nums[L2++];
        }
        for (int i = base; i <= base + k && i <= R2; i++) {
            nums[i] = tmp[i];
        }
    }
};
60400