本文主要是介绍LEETCODE 315. 计算右侧小于当前元素的个数(归并),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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
这篇关于LEETCODE 315. 计算右侧小于当前元素的个数(归并)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!