315. Count of Smaller Numbers After Self(hard)
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]
.
----------------------------------------分割线----------------------------------------------
题目给出一个数组,求出每个元素右边小于它的个数。
分析:
一道BST,从数组尾部开始建树。每个结点除了储存数字(num)和左右孩子结点(left,right)以外,再维护一个变量numOfLeftNode,储存“以当前结点为根结点的子树中,小于等于num的个数(即 左孩子+当前结点 的个数)”
建树时,当插入的数值大于当前结点,递归到右子树,要求结果就可以加上numOfLeftNode了;
当递归到左子树时,当前结点的左孩子数目+1,即numOfLeftNode+1;
代码:
struct Node{
int num;
int numOfLeftNode;
Node* left;
Node* right;
Node(int num,int numOfLeftNode,Node* left=NULL,Node* right=NULL) : num(num),numOfLeftNode(numOfLeftNode),left(left),right(right) {};
};
class Solution{
public:
int insert(Node* tree, int x){
int ans = 0;
bool flag = 0; // 0 for left , 1 for right
while (1){
if ( x > tree->num ){
ans += tree->numOfLeftNode;
if (tree -> right) tree = tree->right;
else {
flag = 1;
break;
}
}
else {
tree->numOfLeftNode++;
if (tree->left) tree = tree -> left;
else break;
}
}
Node* tmp = new Node(x,1);
if (!flag) tree->left = tmp;
else tree->right = tmp;
return ans;
}
vector<int> countSmaller(vector<int>& nums){
int len = nums.size();
vector<int> ans(nums.size(),0);
if (!len) return ans;
Node* head = new Node(nums[len-1],1);
for (int i = nums.size()-2; i >= 0 ; i--)
ans[i] = insert(head,nums[i]);
return ans;
}
};