forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStatistics from a Large Sample.cpp
67 lines (50 loc) · 1.86 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
public:
vector<double> sampleStats(vector<int>& count) {
vector<double> results;
results.push_back(findMin(count));
results.push_back(findMax(count));
const int sum = std::accumulate(std::begin(count), std::end(count), 0);
results.push_back(findMean(count, sum));
if (sum % 2 == 0)
{
const auto left = findMedian(count, sum/2);
const auto right = findMedian(count, sum/2 + 1);
results.push_back ((left + right) / 2.0);
}
else
results.push_back(findMedian(count, sum/2 + 1));
results.push_back(findMode(count));
return results;
}
private:
int findMin(const vector<int> &count) {
const auto minPtr = std::find_if(std::begin(count), std::end(count),
[](const int& c) { return c > 0; });
return minPtr - std::begin(count);
}
int findMax(const vector<int> &count) {
const auto maxPtr = std::find_if(std::rbegin(count), std::rend(count),
[](const int& c) { return c > 0; });
return (std::rend(count) - 1) - maxPtr;
}
int findMode(const vector<int> &count) {
const auto maxCountPtr = std::max_element(begin(count), end(count));
return maxCountPtr - std::begin(count);
}
double findMean(const vector<int> &count, const int &sum) {
auto ratio = 1.0 / sum;
auto mean = 0.0;
for (int i = 0; i < count.size(); ++i)
mean += count[i] * ratio * i;
return mean;
}
int findMedian(const vector<int> &count, int medianCount) {
for (int i = 0; i < count.size(); ++i)
if (count[i] < medianCount)
medianCount -= count[i];
else
return i;
return -1;
}
};