Skip to content

Commit ca16016

Browse files
authored
Update 2615-sum-of-distances.js
1 parent ce6aa56 commit ca16016

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

2615-sum-of-distances.js

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

0 commit comments

Comments
 (0)