Skip to content

Commit ce6aa56

Browse files
authored
Update 2121-intervals-between-identical-elements.js
1 parent 6556704 commit ce6aa56

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

2121-intervals-between-identical-elements.js

+38
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,41 @@
1+
/**
2+
* @param {number[]} arr
3+
* @return {number[]}
4+
*/
5+
const getDistances = function(arr) {
6+
const hash = {}
7+
const n = arr.length
8+
for(let i = 0; i < n; i++) {
9+
const e = arr[i]
10+
if(hash[e] == null) hash[e] = []
11+
hash[e].push(i)
12+
}
13+
const res = []
14+
for(const [k, v] of Object.entries(hash)) {
15+
helper(v)
16+
}
17+
return res
18+
19+
function helper(idxArr) {
20+
let sum = 0
21+
const len = idxArr.length
22+
for(let i = 1; i < len; i++) {
23+
sum += idxArr[i] - idxArr[0]
24+
}
25+
const first = idxArr[0]
26+
res[first] = sum
27+
for(let i = 1; i < len; i++) {
28+
const pre = res[idxArr[i - 1]]
29+
const delta = idxArr[i] - idxArr[i - 1]
30+
const tmp = pre + i * delta - (len - i) * delta
31+
res[idxArr[i]] = tmp
32+
}
33+
}
34+
};
35+
36+
// another
37+
38+
139
/**
240
* @param {number[]} arr
341
* @return {number[]}

0 commit comments

Comments
 (0)