题目链接:https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i]
is the number of smaller elements to the right of nums[i]
.
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0]
.
Every node will maintain a val sum recording the total of number on it's left bottom side, dup counts the duplication. For example, [3, 2, 2, 6, 1], from back to beginning,we would have:
1(0, 1)
\
6(3, 1)
/
2(0, 2)
\
3(0, 1)
When we try to insert a number, the total number of smaller number would be adding dup and sum of the nodes where we turn right.
for example, if we insert 5, it should be inserted on the way down to the right of 3, the nodes where we turn right is 1(0,1), 2,(0,2), 3(0,1), so the answer should be (0 + 1)+(0 + 2)+ (0 + 1) = 4
if we insert 7, the right-turning nodes are 1(0,1), 6(3,1), so answer should be (0 + 1) + (3 + 1) = 5
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
int sz=nums.size();
vector<int> res(sz,0);
node* root=NULL;
for(int i=sz-1;i>=0;i--)
{
root=insert(nums[i],root,res,i,0);
}
return res;
}
private:
struct node{
int val,sum,dup=1;
node* left,*right;
node(int v,int s){val=v;sum=s;left=NULL;right=NULL;}
};
node* insert(int num,node* root,vector<int>& res,int i,int preSum)
{
if(root==NULL)
{
root=new node(num,0);
res[i]=preSum;
}
else if(root->val==num)
{
root->dup++;
res[i]=preSum+root->sum;
}
else if(root->val>num)
{
root->sum++;
root->left=insert(num,root->left,res,i,preSum);
}
else
{
root->right=insert(num,root->right,res,i,preSum+root->dup+root->sum);
}
return root;
}
};
方法二:9二分查找)
利用归并排序,其实就像是求逆序数一样.在将左右两半数组都排序之后,可以对左边数组中的每一个数在右边数组中找到有多少比他小的数.归并排序有很多额外的用途.这种方法的时间复杂度是O(nlog(n)).还有一点可以优化,就是可以再用二分查找来找到第一个大于左边的数.但是不知道能优化多少.
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
if(nums.empty()) return {};
int len=nums.size();
vector<int> res(len,0);
vector<pair<int,int>> vec;
for(int i=0;i<len;i++)
vec.push_back(make_pair(nums[i],i));
mergesort(vec,0,len,res);
return res;
}
private:
void mergesort(vector<pair<int,int>>& nums,int low,int high,vector<int>& ans)
{
if(low+1==high) return;
int mid=low+(high-low)/2,right=mid;
mergesort(nums,low,mid,ans);
mergesort(nums,mid,high,ans);
for(int i=low;i<mid;i++)
{
while(right<high && nums[i].first>nums[right].first) right++;
ans[nums[i].second]+=right-mid;
}
inplace_merge(nums.begin()+low,nums.begin()+mid,nums.begin()+right);
}
};