-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path215.cpp
More file actions
52 lines (46 loc) · 1.42 KB
/
Copy path215.cpp
File metadata and controls
52 lines (46 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Author: btjanaka (Bryon Tjanaka)
// Problem: (Leetcode) 215
// Title: Kth Largest Element in an Array
// Link: https://leetcode.com/problems/kth-largest-element-in-an-array
// Idea: See code comments.
// Difficulty: medium
// Tags: quick-select, priority-queue
// Solution 1: Quick-select - O(n)
class Solution {
public:
// Implementation of quick-select with O(n) extra memory (for simplicity)
// L and R are inclusive
int findKthLargest(vector<int>& nums, vector<int>& buf, int k, int L, int R) {
if (L == R) return nums[L];
int pivot = nums[L + rand() % (R - L + 1)];
int L_i = L, R_i = R;
for (int i = L; i <= R; ++i) {
if (nums[i] > pivot) {
buf[L_i++] = nums[i];
} else if (nums[i] < pivot) {
buf[R_i--] = nums[i];
}
}
for (int i = L; i <= R; ++i) nums[i] = buf[i];
if (k < L_i) return findKthLargest(nums, buf, k, L, L_i - 1);
if (k > R_i) return findKthLargest(nums, buf, k, R_i + 1, R);
return pivot;
}
int findKthLargest(vector<int>& nums, int k) {
srand(time(NULL));
vector<int> buf(nums.size());
return findKthLargest(nums, buf, k - 1, 0, nums.size() - 1);
}
};
// Solution 2: Priority Queue - O(n log n)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> pq;
for (int num : nums) {
pq.push(num);
}
for (int i = 0; i < k - 1; ++i) pq.pop();
return pq.top();
}
};