You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/2600-2699/2615.Sum of Distances/README_EN.md
+81-6Lines changed: 81 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -30,12 +30,12 @@ tags:
30
30
<pre>
31
31
<strong>Input:</strong> nums = [1,3,1,1,2]
32
32
<strong>Output:</strong> [5,0,3,4,0]
33
-
<strong>Explanation:</strong>
34
-
When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5.
33
+
<strong>Explanation:</strong>
34
+
When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5.
35
35
When i = 1, arr[1] = 0 because there is no other index with value 3.
36
-
When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3.
37
-
When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4.
38
-
When i = 4, arr[4] = 0 because there is no other index with value 2.
36
+
When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3.
37
+
When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4.
38
+
When i = 4, arr[4] = 0 because there is no other index with value 2.
39
39
40
40
</pre>
41
41
@@ -64,7 +64,15 @@ When i = 4, arr[4] = 0 because there is no other index with value 2.
64
64
65
65
<!-- solution:start -->
66
66
67
-
### Solution 1
67
+
### Solution 1: Hash Map + Prefix Sum
68
+
69
+
First, use a hash map $d$ to record the list of indices for each element in the array $nums$, that is, $d[x]$ represents the list of all indices in $nums$ where the value is $x$.
70
+
71
+
For each list of indices $idx$ in the hash map $d$, we can calculate the value of $arr[i]$ for each index $i$ in $idx$. For the first index $idx[0]$, the sum of distances to all indices on the right is $right = \sum_{i=0}^{m-1} - idx[0] \times m$. Then, we iterate through $idx$, and for each iteration, compute $ans[idx[i]] = left + right$, then update $left$ and $right$ as follows: $left = left + (idx[i+1] - idx[i]) \times (i+1)$, and $right = right - (idx[i+1] - idx[i]) \times (m-i-1)$.
72
+
73
+
After the iteration, we obtain the array $arr$ corresponding to each element in $nums$, which is stored in $ans$.
74
+
75
+
The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array $nums$.
0 commit comments