
Sponsored
Sponsored
By using a Min-Heap, we can efficiently keep track of the k largest elements. Maintain a heap of size k, and for each element in the array, decide whether to add it to the heap. If you add an element to the heap when it is full, remove the minimum element to maintain the size of the heap as k. At the end, the root of the heap will be the kth largest element.
Time Complexity: O(n log n), where n is the size of the array, because of the sorting operation.
Space Complexity: O(1), as we are modifying the input array in-place.
1#include <iostream>
2#include <vector>
3#include <queue>
4
5int findKthLargest(std::vector<int>& nums, int k) {
6 std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
7 for (int num : nums) {
8 minHeap.push(num);
9 if (minHeap.size() > k) {
10 minHeap.pop();
11 }
12 }
13 return minHeap.top();
14}
15
16int main() {
17 std::vector<int> nums = {3,2,1,5,6,4};
18 int k = 2;
19 std::cout << findKthLargest(nums, k) << std::endl;
20 return 0;
21}We create a min-heap using std::priority_queue by specifying a comparison class std::greater<> to maintain a heap of the k largest elements. By iterating through the elements and maintaining the heap size, the root at the end of the iteration is the kth largest element.
Quickselect is an efficient selection algorithm to find the kth smallest element in an unordered list. The algorithm is related to the quicksort sorting algorithm. It works by partitioning the data, similar to the partitioning step of quicksort, and is based on the idea of reducing the problem size through partitioning.
Average-case Time Complexity: O(n), but worst-case O(n²).
Space Complexity: O(1) for iterative solution, O(log n) for recursive calls due to stack depth.
1#
The quickSelect function recursively partitions the array around pivot elements. The function partition ensures the pivot is in its sorted position with all larger numbers left and smaller numbers right. If the pivot's index equals k, the pivot is the kth largest element. We adjust to 0-based index during each call.