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
| class Solution { int[] count;
public double[] sampleStats(int[] count) { this.count = count; int minimum = Integer.MAX_VALUE, maximum = -1, cnt = 0, mode = 0; double sum = 0; for (int i = 0; i < count.length; ++i) { if (count[i] > 0) { minimum = Math.min(minimum, i); maximum = Math.max(maximum, i); cnt += count[i]; sum += (double) i * count[i]; if (count[i] > count[mode]) mode = i; } } double median = cnt % 2 == 1 ? find(cnt / 2 + 1) : (find(cnt / 2 + 1) + find(cnt / 2)) / 2.0; return new double[]{minimum, maximum, sum / cnt, median, mode}; }
private int find(int i) { for (int k = 0, t = 0; ; ++k) { t += count[k]; if (t >= i) return k; } } }
|