5. Kth Largest Element
Tag:
Quick Sort, Sort
Description:
Find K-th largest element in an array.
Main Idea:
It’s not recommended to sort the array, because it’s time-costing.
Partition problem. In this problem, we only need to find the kth large number, partition would be our tool. If this problem wants to find the first k large numbers, then we need to use priority queue structure.
At the first, write the partition template. Then, compare the k with the position of the partition. Keep partition until it’s get the target result.
Code explain:
- In this problem, though there are three functions: main(), helper, and partition, the structure is simple.
- Partition function is template, which is tagged at the end.
- The main() function is to check is corner case and call the helper function.
- The helper function is the key point. Beside check the pointers(l ,r), IF the position is at the k place, return the result; ELSE IF position is larger than k, partition the former part; ELSE partition the latter part.
Tips/Notes:
- Notice in helper function’s input, k is not the index, while is position is.
- Don’t mess up the partition part after comparison. If position+1 > k, partition [l, position-1]; position+1 < k, partition [position + 1, r].
Time/Space Cost:
Time Cost: O ( n ) \ O(n) O(n)
Code:
class Solution {
public:
/**
* @param n: An integer
* @param nums: An array
* @return: the Kth largest element
*/
int kthLargestElement(int n, vector<int> &nums) {
// write your code here
int len = nums.size();
if(n < 0 || n > len || len == 0){
return 0;
}
return helper(len - n + 1, nums, 0, len-1);
}
int helper(int k, vector<int> &nums, int l, int r){
if(l == r)
return nums[l];
int position = partition(nums, l, r);
// k is the kth large nums, i is the index.
if(position + 1 == k){
return nums[position];
}
else if(position + 1 < k){
return helper(k, nums, position + 1, r);
}
else {
return helper(k, nums, l, position - 1);
}
}
int partition(vector<int> &nums, int l, int r){
int left = l, right = r;
int pivot = nums[left];
while(left < right){
while(left < right && nums[right] >= pivot){
right--;
}
nums[left] = nums[right];
while(left < right && nums[left] <= pivot){
left++;
}
nums[right] = nums[left];
}
nums[left] = pivot;
return left;
}
};
Partition Template:
class Solution {
public:
int partition(vector<int> &nums, int l, int r){
int left = l, right = r;
int pivot = nums[left];
while(left < right){
while(left < right && nums[right] >= pivot){
right--;
}
nums[left] = nums[right];
while(left < right && nums[left] <= pivot){
left++;
}
nums[right] = nums[left];
}
nums[left] = pivot;
return left;
}
};