【小白爬Leetcode315】6.4(搜索二叉树版) 计算右侧小于当前元素的个数 Count of Smaller Numbers After Self
Leetcode 315
h
a
r
d
\color{#FF0000}{hard}
hard
点击进入原题链接:Leetcode 315 计算右侧小于当前元素的个数 Count of Smaller Numbers After Self
题目
Discription
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].
中文解释
给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
思路一 归并排序+pair绑定原序数:
【小白爬Leetcode315】4.6 计算右侧小于当前元素的个数 Count of Smaller Numbers After Self
思路二 搜索二叉树 Binary Search Tree
原问题等价于这个问题:反转nums
数组后(姑且称为reversed_nums
),寻找reversed_nums
每一个元素reversed_nums[i]
前(0~i-1
)有多少个小于小于它的元素。
搜索二叉树(Binary Search Tree) 就可以很好地完成这个任务:
- 每个节点都有一个
count_left
的值,记录这个节点左侧搜索元素的数量。这个不难办到:只要在每次新节点插入二叉树的时候,遇到小于等于当前节点值的元素(即insert->val <= root->val
),就使root->count_left ++
即可。 - 同时还有一个
count
值记录插入当前节点的时候,所有比当前节点小的元素个数。这个也不难办到:在插入的时候,遇到insert->val > root->val
的情况,就让count += root->count_left+1
即可。
完整代码如下:
class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
int len = nums.size();
vector<int> ret(len,0); //初始化结果数组
if(len==0){
return ret;
}
TreeNode* root = new TreeNode(nums[len-1]); //注意这里对空的nums是敏感的,所以在前面要把空数组排除掉
for(int i=nums.size()-2;i>=0;i--){ //最后一个数不用管它,逆序数肯定是0
int count = 0;
ret[i] = count_Left_Insert_BST(root,new TreeNode(nums[i]),count);}
return ret;
}
private:
struct TreeNode{
int val;
int left_count = 0;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
TreeNode(int x):val(x){};
};
int count_Left_Insert_BST(TreeNode*root,TreeNode*insert,int& count){
if(root->val>=insert->val){
root->left_count++;
if(root->left){
count_Left_Insert_BST(root->left,insert,count);
}else{
root->left = insert;
}
}
else{
count += root->left_count;
count++;
if(root->right){
count_Left_Insert_BST(root->right,insert,count);
}else{
root->right = insert;
}
}
return count;
}
};
时间复杂度: 每插入一个节点为 logn ,一共n个节点要插入,因此为O(nlogn) ,和方法一是一样的时间复杂度
空间复杂度: 堆区开辟了额外的n个树节点,因此为O(n)。