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]
.
Subscribe to see which companies asked this question
struct TreeNodei {
int val;
int count;
struct TreeNodei *left;
struct TreeNodei *right;
TreeNodei(int x) : val(x), count(1), left(NULL), right(NULL)
//count 初始化为1是表示以这个Node为根节点(包括它自己全部左子树的节点数)
};
class Solution {
private:
int insertNode(TreeNodei *root, TreeNodei* curNode) {
int count = 0;//count表示curNode从最右端到它所在的位置比它小的数目
//和node->count是不同的概念
while (true)
{
if (root->val>=curNode->val)
{
root->count++;
if (root->left)
{
root = root->left;
}
else
{
root->left = curNode;
break;
}
}
else
{
count += root->count;
if (root->right)
{
root = root->right;
}
else
{
root->right = curNode;
break;
}
}
}
return count;
}
public:
vector<int> countSmaller(vector<int>& nums) {
vector<int> retVtr(nums.size());
if (nums.size() == 0)
return retVtr;
TreeNodei *root = new TreeNodei(nums[nums.size()-1]);
retVtr[nums.size()-1] = 0;
for (int i=nums.size()-2; i>=0; i--)
{
TreeNodei* curNode= new TreeNodei(nums[i]);
int val = insertNode(root, curNode);
retVtr[i] = val;
}
return retVtr;
}
};