力扣2615.等值距离和
力扣2615.等值距离和
-
分组求距离和
-
class Solution { public: vector<long long> distance(vector<int>& nums) { int n = nums.size(); unordered_map<int, vector<int>> groups; for (int i = 0; i < n; ++i) groups[nums[i]].emplace_back(i); vector<long long> res(n); for(auto &[_,a] : groups) { int m = a.size(); long long lsum = 0,rsum = accumulate(a.begin(),a.end(),0LL); for(int i=0;i<m;i++) { rsum -= a[i]; res[a[i]] = (long long)a[i] * i - lsum + rsum - (long long)a[i] * (m - i - 1); lsum += a[i]; } } return res; } };
原文地址:https://blog.csdn.net/Pisasama/article/details/140145221
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!