Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1bf168e

Browse files
committed
Add solution #2615
1 parent 2570aae commit 1bf168e

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,759 LeetCode solutions in JavaScript
1+
# 1,760 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1680,6 +1680,7 @@
16801680
2570|[Merge Two 2D Arrays by Summing Values](./solutions/2570-merge-two-2d-arrays-by-summing-values.js)|Easy|
16811681
2579|[Count Total Number of Colored Cells](./solutions/2579-count-total-number-of-colored-cells.js)|Medium|
16821682
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|
16831684
2618|[Check if Object Instance of Class](./solutions/2618-check-if-object-instance-of-class.js)|Medium|
16841685
2619|[Array Prototype Last](./solutions/2619-array-prototype-last.js)|Easy|
16851686
2620|[Counter](./solutions/2620-counter.js)|Easy|

solutions/2615-sum-of-distances.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
};

0 commit comments

Comments
 (0)