-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample_stats.cpp
More file actions
102 lines (95 loc) · 3.92 KB
/
sample_stats.cpp
File metadata and controls
102 lines (95 loc) · 3.92 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* =====================================================================================
*
* Filename: sample_stats.cpp
*
* Description: 1093. Statistics from a Large Sample.
* https://leetcode.com/problems/statistics-from-a-large-sample/
*
* Version: 1.0
* Created: 03/03/23 23:31:59
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <numeric>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::vector;
class Solution {
public:
vector<double> sampleStats(vector<int>& count) {
int min_stat = 255, max_stat = 0, mode = 0;
int64_t sum = 0;
double median = 0.0;
int cur_cnt = 0;
int max_cnt = 0;
int total_cnt = std::accumulate(count.begin(), count.end(), 0);
int m1 = (total_cnt + 1) / 2;
int m2 = (total_cnt % 2 == 0) ? (m1 + 1) : m1;
for (int i = 0; i < count.size(); i++) {
if (count[i] <= 0) {
continue;
}
min_stat = std::min(min_stat, i);
max_stat = std::max(max_stat, i);
sum += (int64_t)i * count[i];
if ((cur_cnt < m1) && (cur_cnt + count[i] >= m1)) {
median = (double)i / 2;
}
if ((cur_cnt < m2) && (cur_cnt + count[i] >= m2)) {
median += (double)i / 2;
}
cur_cnt += count[i];
if (count[i] > max_cnt) {
mode = i;
max_cnt = count[i];
}
}
return {(double)min_stat, (double)max_stat, (double)sum / total_cnt, median,
(double)mode};
}
};
TEST(Solution, sampleStats) {
vector<std::pair<vector<int>, vector<double>>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, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
vector<double>{1.00000, 4.00000, 2.18182, 2.00000, 1.00000}), */
};
for (auto& c : cases) {
EXPECT_THAT(Solution().sampleStats(c.first),
testing::ElementsAreArray(c.second));
}
}