1.思路就是借助构建二叉搜索树,在构建的过程中存储和找到所需要的信息。
struct node{
int val,count,simil;
node* left,*right;
node(int v):val(v),count(1),simil(1),left(NULL),right(NULL)
{
}
};
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
int n=nums.size();
if(n==0) return vector<int>();
node* root=new node(nums[n-1]);
vector<int> ans(n);
ans[n-1]=0;
for(int i=n-2;i>=0;i--){
ans[i]=creat(root,nums[i]);
}
return ans;
}
int creat(node* root,int val){
if(val>root->val){
if(root->right){
return creat(root->right,val)+root->count;
}else{
node* tp=new node(val);
root->right=tp;
return root->count;
}
}
else if(val<root->val){
root->count++;
if(root->left){
return creat(root->left,val);
}else{
node* tp=new node(val);
root->left=tp;
return 0;
}
}
else
return (++root->count)-(++root->simil);
}
};