215. 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.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Solution
C++
Sol1:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int> > pq;
for(int n: nums) {
pq.push(n);
if(pq.size() > k) pq.pop();
}
return pq.top();
}
};
Sol2:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
k = nums.size() - k;
int l = 0, r = nums.size() - 1;
while(l < r) {
int pivotIndex = partition(nums,l,r);
if(pivotIndex < k) l = pivotIndex + 1;
else if(pivotIndex > k) r = pivotIndex - 1;
else break;
}
return nums[k];
}
int partition(vector<int>& a, int left, int right) {
int pivotIndex = left+(right-left)/2;
int pivot = a[pivotIndex];
swap(a[pivotIndex], a[right]);
int l = left, r = right-1;
while(l <= r) {
if(a[l] < pivot) ++l;
else if(a[r] >= pivot) --r;
else {
swap(a[l], a[r]);
++l;
--r;
}
}
swap(a[l], a[right]);
return l;
}
};
Explanation
Sol1: Min heap
Time: O ( n l o g k ) O(nlogk) O(nlogk)
Sol2: Partition
Time: average O ( N ) O(N) O(N) ,worst O ( N 2 ) O(N^2) O(N2)
In average, this algorithm reduces the size of the problem by approximately one half after each partition, giving the recurrence T(n) = T(n/2) + O(n) with O(n) being the time for partition. The solution is T(n) = O(n), which means we have found an average linear-time solution. However, in the worst case, the recurrence will become T(n) = T(n - 1) + O(n) and T(n) = O(n^2).