-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2615.cpp
More file actions
28 lines (28 loc) · 923 Bytes
/
2615.cpp
File metadata and controls
28 lines (28 loc) · 923 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
vector<long long> distance(vector<int>& nums) {
unordered_map<int, vector<int>> mp;
int n = nums.size();
for (int i = 0; i < n; ++i) {
mp[nums[i]].push_back(i);
}
vector<long long> res(n, 0);
for (auto& [num, positions] : mp) {
if (positions.size() == 1) continue;
int m = positions.size();
long long cum = 0;
for (int i = 1; i < m; ++i) {
cum += positions[i] - positions[0];
}
res[positions[0]] = cum;
for (int i = 1; i < m; ++i) {
long long right = m - i;
long long left = i;
cum -= right * (positions[i] - positions[i - 1]);
cum += left * (positions[i] - positions[i - 1]);
res[positions[i]] = cum;
}
}
return res;
}
};