leetcode:Count of Smaller Numbers After Self

本文介绍了一种使用树结构的方法来计算给定整数数组中每个元素右侧有多少个较小的元素,提供了算法实现和详细解释。

摘要生成于 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].

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值