Skip to content

Commit a6015ed

Browse files
authored
Create 2615-sum-of-distances.js
1 parent 9b8bd81 commit a6015ed

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

2615-sum-of-distances.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
const distance = function(nums) {
6+
const n = nums.length
7+
const res = Array(n).fill(0)
8+
const hash = {}
9+
for(let i = 0; i < n; i++) {
10+
const e = nums[i]
11+
if(hash[e] == null) hash[e] = []
12+
hash[e].push(i)
13+
}
14+
15+
const keys = Object.keys(hash)
16+
for(const k of keys) {
17+
const arr = hash[k]
18+
const totalSum = arr.reduce((ac, e) => ac + e, 0)
19+
let preSum = 0
20+
if(arr.length < 2) continue
21+
for(let i = 0, len = arr.length; i < len; i++) {
22+
const idx = arr[i]
23+
const postSum = totalSum - (preSum + idx)
24+
25+
res[idx] += idx * i
26+
res[idx] -= preSum
27+
res[idx] -= idx * (len - 1 - i)
28+
res[idx] += postSum
29+
30+
preSum += idx
31+
}
32+
}
33+
34+
35+
return res
36+
};

0 commit comments

Comments
 (0)