题目链接:https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self/
题目描述
给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
示例:
输入: [5,2,6,1]
输出: [2,1,1,0]
解释:
5 的右侧有 2 个更小的元素 (2 和 1).
2 的右侧仅有 1 个更小的元素 (1).
6 的右侧有 1 个更小的元素 (1).
1 的右侧有 0 个更小的元素.
思路
首先,由于时间复杂度要低于 O(n^2),所以时间复杂度至多为O(nlogn)。考虑到至少需要遍历一遍数据O(n),所以在每次遍历操作的时间复杂度需要控制在O(logn)。
在该题目中
1 二叉搜索树
复杂度分析
时间复杂度:O(nlogn)
空间复杂度:O(n)
class Solution {
/*
* 构建二叉搜索树;倒序插入
* 时间复杂度O(nlogn)空间复杂度O(n)
*/
struct TreeNode {
TreeNode *left;
TreeNode *right;
int val;
int cnt = 0; // 左子树节点的个数
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 二叉搜索树插入新节点
TreeNode* insert(TreeNode *root, int val, vector<int> &ret, int index){
if (root == nullptr) return new TreeNode(val);
// 小于当前节点值放入左子树
if(val <= root->val){
root->cnt ++;
root->left = insert(root->left, val, ret, index);
}
// 大于当前节点值则放入右子树
else{
ret[index] += root->cnt + 1; // 将路径上节点的左子树节点数累加
root->right = insert(root->right, val, ret,index);
}
return root;
}
public:
vector<int> countSmaller(vector<int>& nums) {
TreeNode *root = nullptr;
vector<int> ret(nums.size());
for (int i = nums.size()-1; i >=0 ; --i) {
root = insert(root, nums[i], ret, i);
}
return ret;
}
};