Problem Description :
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.
- Quick select avg time is O(n)
T(n) = T(n / 2 ) + O(n);
int findKthLargest(vector<int>& nums, int k)
{
int n = nums.size();
int left = 0, right = n - 1;
int pos = partition(nums, left, right);
while (pos + 1 != k ) {
if (pos + 1 > k)
right = pos - 1;
else
left = pos + 1;
pos = partition(nums, left, right);
}
return nums[pos];
// while(1)
// {
// int pos=partition(nums,left,right);
// if(pos==k-1)return nums[pos];
// if(pos>k-1)right=pos-1;
// else left=pos+1;
// }
}
int partition(vector<int> & nums, int l, int r)
{
int pivot = nums[l];
int left = l + 1, right = r;
while (left <= right)
{
while (left <= right && nums[left] >= pivot) ++left;
while (left <= right && nums[right] <= pivot) --right;
if (left <= right)
swap(nums[left++], nums[right--]);
}
swap(nums[l], nums[right]);
return right;
}
- Using Heap Sort.
// buildheap is O(n) in an amortized sense;
// O(klogn) for k times of max_heapify;
class Solution {
public:
void buildheap(vector<int> & nums)
{
heap_size = nums.size();
for (int i = (heap_size >> 1) - 1; i >= 0; --i) //start from the last non-leaf node;
adjustHeap(nums, i);
}
void adjustHeap(vector<int> & nums, int i)
{
int left = i * 2 + 1;
int right = i * 2 + 2;
int max = i;
if ( left < heap_size && nums[left] > nums[max] )
max = left;
if ( right < heap_size && nums[right] > nums[max] )
max = right;
if (max != i)
{
swap(nums[i], nums[max]);
adjustHeap(nums, max); // adjust the children top-down
}
}
int findKthLargest(vector<int>& nums, int k) {
buildheap(nums);
for (int i = 0; i < k; ++i)
{
swap(nums[0], nums[heap_size - 1]);
heap_size--;
adjustHeap(nums, 0);
}
return nums[heap_size];
}
private:
int heap_size;
};
- Using priority queue
int findKthLargest(vector<int> & nums, int k)
{
priority_queue<int> pq(nums.begin(), nums.end());//default is max_heap;
for (int i = 0; i < k - 1; ++i)
pq.pop();
return pq.top();
}
4.Using multiset Container:
int findKthLargest(vector<int>& nums, int k) {
multiset<int> mset;
int n = nums.size();
for (int i = 0; i < n; i++) {
mset.insert(nums[i]);
if (mset.size() > k)
mset.erase(mset.begin());
}
return *mset.begin();
}