forked from adnanaziz/EPIJudge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkth_largest_element_in_long_array.cc
43 lines (37 loc) · 1.51 KB
/
kth_largest_element_in_long_array.cc
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
#include <algorithm>
#include <functional>
#include <vector>
#include "test_framework/generic_test.h"
using std::greater;
using std::vector;
int FindKthLargestUnknownLength(vector<int>::const_iterator stream_begin,
const vector<int>::const_iterator& stream_end,
int k) {
vector<int> candidates;
while (stream_begin != stream_end) {
candidates.emplace_back(*stream_begin++);
if (size(candidates) == 2 * k - 1) {
// Reorders elements about median with larger elements appearing before
// the median.
nth_element(begin(candidates), begin(candidates) + k - 1, end(candidates),
greater<int>());
// Resize to keep just the k largest elements seen so far.
candidates.resize(k);
}
}
// Finds the k-th largest element in candidates.
nth_element(begin(candidates), begin(candidates) + k - 1, end(candidates),
greater<int>());
return candidates[k - 1];
}
int FindKthLargestUnknownLengthWrapper(const vector<int>& stream, int k) {
return FindKthLargestUnknownLength(stream.cbegin(), stream.cend(), k);
}
// clang-format off
int main(int argc, char* argv[]) {
std::vector<std::string> args {argv + 1, argv + argc};
std::vector<std::string> param_names {"stream", "k"};
return GenericTestMain(args, "kth_largest_element_in_long_array.cc", "kth_largest_element_in_long_array.tsv", &FindKthLargestUnknownLengthWrapper,
DefaultComparator{}, param_names);
}
// clang-format on