每日一题:大样本统计
题目链接:https://leetcode.cn/problems/statistics-from-a-large-sample/
# 解题思路
直接按题意模拟遍历即可!
求中位数有个技巧:
- 直接遍历到第
n / 2 + 1
个数,这样如果n
为奇数,该数就是中位数,否则,就是该数和它前面的一个数的平均数就是中位数
# 执行结果
# 代码
class Solution { | |
public double[] sampleStats(int[] count) { | |
int n = count.length; | |
double sum = 0; | |
int cnt = 0; | |
int max = -1; | |
int min = 256; | |
int maxCount = 0; | |
int mode = 0; | |
for (int i = 0; i < n; ++i) { | |
if (count[i] > 0) { | |
max = Math.max(i, max); | |
min = Math.min(i, min); | |
sum += (double) i * count[i]; | |
cnt += count[i]; | |
if (count[i] > maxCount) { | |
maxCount = count[i]; | |
mode = i; | |
} | |
} | |
} | |
double median = 0; | |
// 寻找第 cnt / 2 + 1 个数 | |
int k = 0; | |
int mid = cnt / 2 + 1; | |
while (k < n) { | |
if (mid <= count[k]) { | |
median = k; | |
if (cnt % 2 == 0) { | |
// 偶数个 | |
if (mid == 1) { | |
// 在前一个桶内 | |
--k; | |
while (k > 0 && count[k] <= 0) --k; | |
} | |
median = (median + k) / 2; | |
} | |
break; | |
} | |
mid -= count[k++]; | |
} | |
return new double[] {min, max, sum / cnt, median, mode}; | |
} | |
} |