File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-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 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[] }
You can’t perform that action at this time.
0 commit comments