File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments