Skip to content

Commit bc0b54a

Browse files
authored
Create 1093-statistics-from-a-large-sample.js
1 parent a2a27d0 commit bc0b54a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {number[]} count
3+
* @return {number[]}
4+
*/
5+
const sampleStats = function(count) {
6+
const n = count.length
7+
let numElems = 0
8+
let sum = 0
9+
let min = n - 1
10+
let max = 0
11+
let modVal = 0
12+
let modIdx = 0
13+
for (let i = 0; i < n; i++) {
14+
if (count[i]) {
15+
min = Math.min(i, min)
16+
max = Math.max(i, max)
17+
if (count[i] > modVal) {
18+
modVal = count[i]
19+
modIdx = i
20+
}
21+
sum += i * count[i]
22+
numElems += count[i]
23+
}
24+
}
25+
const half = Math.floor(numElems / 2)
26+
let median
27+
for (let i = 0, c = 0, last = 0; i < n; i++) {
28+
if (count[i]) {
29+
c += count[i]
30+
if (c > half) {
31+
if (numElems % 2 === 0 && c - count[i] === half) {
32+
median = (i + last) / 2
33+
} else {
34+
median = i
35+
}
36+
break
37+
}
38+
last = i
39+
}
40+
}
41+
return [min, max, sum / numElems, median, modIdx]
42+
}

0 commit comments

Comments
 (0)