Solution1 归并排序:
class Solution { public: int reversePairs(vector<int>& nums) { mergesort(nums,0,nums.size()-1); return res; } int res=0; void mergesort(vector<int>& nums, int left, int right){ if(left>=right) return; int mid=left+(right-left)/2; mergesort(nums,left,mid); mergesort(nums,mid+1,right); int j=mid+1; int i=left; vector<int> tmp; while(i<=mid && j<=right){ if(nums[i]<=nums[j]){ res+=j-1-(mid+1)+1; tmp.push_back(nums[i++]); }else{ tmp.push_back(nums[j++]); } } while(i<=mid){ res+=right-(mid+1)+1; tmp.push_back(nums[i++]); } while(j<=right){ tmp.push_back(nums[j++]); } for(int i=left;i<=right;i++){ nums[i]=tmp[i-left]; } } };
Solution2 FenwickTree:
class Solution { public: struct Number{ int index; int num; }; int reversePairs(vector<int>& nums) { int n=nums.size(); vector<Number> vs; for(int i=0;i<n;i++){ vs.push_back({i,nums[i]}); } sort(vs.begin(),vs.end(),[](Number n1, Number n2){ return n1.num<n2.num; }); vector<int> rank(n); int rk=0; int pre=INT_MIN; for(int i=0;i<n;i++){ if(vs[i].num==pre) rank[vs[i].index]=rk; else { rank[vs[i].index]=i+1; rk=i+1; } pre=vs[i].num; } vector<int> fenwick(n+1); int res=0; for(int i=n-1;i>=0;i--){ if(rank[i]!=1){ res+=find(fenwick,rank[i]-1); } update(fenwick,rank[i]); } return res; } void update(vector<int>& fenwick, int idx){ while(idx<=fenwick.size()-1){ fenwick[idx]+=1; idx+=(idx&-idx); } } int find(vector<int>& fenwick, int idx){ int res=0; while(idx>=1){ res+=fenwick[idx]; idx-=(idx&-idx); } return res; } };