forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statistics-from-a-large-sample.cpp
32 lines (26 loc) · 1.25 KB
/
statistics-from-a-large-sample.cpp
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
// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<double> sampleStats(vector<int>& count) {
const double mi = distance(count.cbegin(), find_if(count.cbegin(), count.cend(),
[](int x) { return x != 0; }));
const double ma = count.size() - 1 -
distance(count.crbegin(), find_if(count.crbegin(), count.crend(),
[](int x) { return x != 0; }));
const auto& n = accumulate(count.cbegin(), count.cend(), 0);
double total = 0.0;
for (int i = 0; i < count.size(); ++i) {
total += double(i) * count[i];
}
const double mean = total / n;
const double mode = distance(count.cbegin(), max_element(count.cbegin(), count.cend()));
for (int i = 1; i < count.size(); ++i) {
count[i] += count[i - 1];
}
const auto& median1 = distance(count.cbegin(), lower_bound(count.cbegin(), count.cend(), (n + 1) / 2));
const auto& median2 = distance(count.cbegin(), lower_bound(count.cbegin(), count.cend(), (n + 2) / 2));
const double median = (median1 + median2) / 2.0;
return {mi, ma, mean, median, mode};
}
};