[LeetCode315] Count of Smaller Numbers After Self

本文介绍了一种使用二叉搜索树(BST)解决数组问题的方法,具体为计算数组中每个元素右侧小于它的元素数量。通过构建BST并利用其性质进行查询和插入操作,实现高效计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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].

Hide Company Tags Google

就用BST吧!O(nlogn) w/ O(n) spcae!

class Solution {
public:
    class TreeNode{
      public:
      int val, cnt;
      TreeNode *left, *right;
      TreeNode(int val, int cnt){
          this->val = val;
          this->cnt = cnt;
          this->left = nullptr;
          this->right = nullptr;
      }
    };
    vector<int> countSmaller(vector<int>& nums) {
        TreeNode* root = nullptr;
        vector<int> res(nums.size());
        for(int i = nums.size()-1; i>=0; --i){
            TreeNode* node = new TreeNode(nums[i], 0);
            root = insertNode(root, node);
            res[i] = query(root, nums[i]);
        }
        return res;
    }

    TreeNode* insertNode(TreeNode* root, TreeNode* node){
        if(!root) return node;
        TreeNode* cur = root;
        while(cur){
            if(cur->val > node->val){//insert to left subtree
                ++cur->cnt;
                if(!cur->left){
                    cur->left = node;
                    break;
                }else cur = cur->left;
            }else{//insert to right subtree;
                if(!cur->right){
                    cur->right = node;
                    break;
                }else cur = cur->right;
            }
        }
        return root;
    }
    int query(TreeNode* root, int target){
        if(!root) return 0;
        TreeNode* cur = root;
        int count = 0;
        while(cur){
            if(cur->val > target){
                cur = cur->left;
            }else if(cur->val < target) {
                count += cur->cnt + 1;
                cur = cur->right;
            }
            else return (cur->cnt) + count;
        }
        return 0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值