File tree 2 files changed +46
-1
lines changed
2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,759 LeetCode solutions in JavaScript
1
+ # 1,760 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1680
1680
2570|[ Merge Two 2D Arrays by Summing Values] ( ./solutions/2570-merge-two-2d-arrays-by-summing-values.js ) |Easy|
1681
1681
2579|[ Count Total Number of Colored Cells] ( ./solutions/2579-count-total-number-of-colored-cells.js ) |Medium|
1682
1682
2594|[ Minimum Time to Repair Cars] ( ./solutions/2594-minimum-time-to-repair-cars.js ) |Medium|
1683
+ 2615|[ Sum of Distances] ( ./solutions/2615-sum-of-distances.js ) |Medium|
1683
1684
2618|[ Check if Object Instance of Class] ( ./solutions/2618-check-if-object-instance-of-class.js ) |Medium|
1684
1685
2619|[ Array Prototype Last] ( ./solutions/2619-array-prototype-last.js ) |Easy|
1685
1686
2620|[ Counter] ( ./solutions/2620-counter.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 2615. Sum of Distances
3
+ * https://leetcode.com/problems/sum-of-distances/
4
+ * Difficulty: Medium
5
+ *
6
+ * You are given a 0-indexed integer array nums. There exists an array arr of length nums.length,
7
+ * where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there
8
+ * is no such j, set arr[i] to be 0.
9
+ *
10
+ * Return the array arr.
11
+ */
12
+
13
+ /**
14
+ * @param {number[] } nums
15
+ * @return {number[] }
16
+ */
17
+ var distance = function ( nums ) {
18
+ const valueIndices = new Map ( ) ;
19
+ const result = new Array ( nums . length ) . fill ( 0 ) ;
20
+
21
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
22
+ if ( ! valueIndices . has ( nums [ i ] ) ) {
23
+ valueIndices . set ( nums [ i ] , [ ] ) ;
24
+ }
25
+ valueIndices . get ( nums [ i ] ) . push ( i ) ;
26
+ }
27
+
28
+ for ( const indices of valueIndices . values ( ) ) {
29
+ let prefixSum = 0 ;
30
+ for ( let i = 1 ; i < indices . length ; i ++ ) {
31
+ prefixSum += indices [ i ] - indices [ 0 ] ;
32
+ }
33
+
34
+ result [ indices [ 0 ] ] = prefixSum ;
35
+
36
+ for ( let i = 1 ; i < indices . length ; i ++ ) {
37
+ const diff = indices [ i ] - indices [ i - 1 ] ;
38
+ prefixSum += diff * ( i - ( indices . length - i ) ) ;
39
+ result [ indices [ i ] ] = prefixSum ;
40
+ }
41
+ }
42
+
43
+ return result ;
44
+ } ;
You can’t perform that action at this time.
0 commit comments