-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode2615.cpp
More file actions
42 lines (32 loc) · 1.01 KB
/
leetcode2615.cpp
File metadata and controls
42 lines (32 loc) · 1.01 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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> ans(n, 0);
for (auto &it : mp) {
vector<int> &pos = it.second;
int m = pos.size();
if (m == 1) continue;
vector<long long> prefix(m, 0);
prefix[0] = pos[0];
for (int i = 1; i < m; i++) {
prefix[i] = prefix[i - 1] + pos[i];
}
for (int i = 0; i < m; i++) {
long long left = 0, right = 0;
if (i > 0) {
left = 1LL * i * pos[i] - prefix[i - 1];
}
if (i < m - 1) {
right = (prefix[m - 1] - prefix[i]) - 1LL * (m - i - 1) * pos[i];
}
ans[pos[i]] = left + right;
}
}
return ans;
}
};