class Solution {
public: // 将count声明为publicvector<int> count; vector<int> indexs,tmp;public:vector<int> countSmaller(vector<int>& nums) {//归并int left=0;int right=nums.size()-1;//计数// vector<int> count(nums.size()); count=vector<int>(nums.size());for(int i=0;i<nums.size();i++){count[i]=0;}//index // vector<int> indexs(nums.size());indexs=vector<int>(nums.size());for(int i=0;i<nums.size();i++){indexs[i]=i;}tmp=vector<int>(nums.size());mergeSort(left,right,nums);// vector<int> counts;// for(int i=0;i<nums.size();i++)// counts.push_back(n[nums_copy[i]]);return count;}void mergeSort(int left,int right,vector<int>& nums){if(left>=right)return ;int mid=left+(right-left)/2;mergeSort(left,mid,nums);mergeSort(mid+1,right,nums);merge(left,right,nums);}void merge(int left,int right,vector<int>& nums){int mid=left+(right-left)/2;int i=left;int j=mid+1;// vector<int> tmp;int k=0;while(i<=mid && j<=right){if(nums[indexs[i]]>nums[indexs[j]]){count[indexs[i]]+=(right-j)+1;tmp[k++]=indexs[i++];}else{tmp[k++]=indexs[j++];}}while(i<=mid){tmp[k++]=indexs[i++];}while(j<=right){tmp[k++]=indexs[j++];}for(int i=0;i<k;i++){indexs[left+i]=tmp[i];}// tmp.clear();}};
Focus:
1 (int left,int right,vector& nums) &没有用取址符会超出内存
2 点在于indexs 按index顺序归并,比较按里面元素
3 tmp index count