[LeetCode] Sum of Distances

2615. Sum of Distances

You are given a 0-indexed integer array nums. There exists an array arr of length nums.length, where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there is no such j, set arr[i] to be 0.

Return the array arr.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<long long> distance(vector<int>& nums) {
unordered_map<int, vector<int>> mp;
vector<long long> res(nums.size());
for(int i = 0; i < nums.size(); i++) {
mp[nums[i]].push_back(i);
}
for(auto [k,v] : mp) {
long long le = 0, ri = accumulate(begin(v), end(v), 0ll);
long long lec = 0, ric = v.size();
for(int i = 0; i < v.size(); i++) {
ri -= v[i];
ric -= 1;
res[v[i]] = abs(le - lec * v[i]) + abs(ri - ric * v[i]);
le += v[i];
lec += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/09/PS/LeetCode/sum-of-distances/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.