leetcode 2121. 相同元素的间隔之和
作者:互联网
1 class Solution { 2 public: 3 vector<long long> getDistances(vector<int>& arr) { 4 unordered_map<int,vector<int>>mp; 5 int n=arr.size(); 6 vector<long long>ans(n); 7 unordered_map<int,long long>presum,suffsum; 8 unordered_map<int,int>precnt,suffcnt; 9 for(int i=0;i<n;i++) 10 { 11 presum[arr[i]]+=i; 12 precnt[arr[i]]++; 13 long long tmp=presum[arr[i]]; 14 ans[i]+=1ll*(i)*(precnt[arr[i]] )-tmp; 15 } 16 for(int i=n-1;i>=0;i--) 17 { 18 suffsum[arr[i]]+=i; 19 suffcnt[arr[i]]++; 20 long long tmp=suffsum[arr[i]]; 21 ans[i]+=tmp-1ll*(suffcnt[arr[i]])*i; 22 23 } 24 return ans; 25 26 /* 27 x1...xj...xn; 28 xj-x1+... +xj+1-xj+... xn-xj 29 */ 30 } 31 };
标签:2121,xj,arr,+...,suffcnt,间隔,suffsum,unordered,leetcode 来源: https://www.cnblogs.com/matt-su/p/15749913.html