<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 {
    int left(int i) {
        return (i+1)*2-1;
    }
    int right(int i) {
        return (i+1)*2;
    }
    int parent(int i) {
        return (i+1)/2-1;
    }
    void go_up(vector<int>& heap, int i) {
        if(parent(i) < 0)
            return;
        if(heap[i] > heap[parent(i)]) {
            swap(heap[i], heap[parent(i)]);
            go_up(heap, parent(i));
        }
    }
    void go_down(vector<int>& heap, int i) {
        if(left(i) >= heap.size())
            return;
        if(right(i) < heap.size() && heap[right(i)] > heap[left(i)]) {
            if(heap[i] < heap[right(i)]) {
                swap(heap[i], heap[right(i)]);
                go_down(heap, right(i));
            }
        } else {
            if(heap[i] < heap[left(i)]) {
                swap(heap[i], heap[left(i)]);
                go_down(heap, left(i));
            }
        }
    }
    void push_heap(vector<int>& heap, int i, int k) {
        if(heap.size() == 0) {
            heap.push_back(i);
            return;
        }
        int top = heap[0];
        heap[0] = i;
        go_down(heap, 0);
        heap.push_back(top);
        go_up(heap, heap.size()-1);
        if(heap.size() > k)
            heap.pop_back();
    }
    void pop_heap(vector<int>& heap) {
        heap[0] = heap.back();
        heap.pop_back();
        go_down(heap, 0);
    }
public:
    int findKthLargest(vector<int>& nums, int k) {
        vector<int> heap;
        int s = 1;
        while(s < k*16)
            s*=2;
        heap.reserve(s+1);
        for(int i : nums) {
            push_heap(heap, i, s);
        }
        for(int i = 0;i < k-1;i++) {
            pop_heap(heap);
        }
        return heap[0];
    }
};
63100