File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+
1
39
/**
2
40
* @param {number[] } arr
3
41
* @return {number[] }
You can’t perform that action at this time.
0 commit comments