【小白爬Leetcode315】6.4 (搜索二叉树版)计算右侧小于当前元素的个数 Count of Smaller Numbers After Self

【小白爬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) 就可以很好地完成这个任务:

  1. 每个节点都有一个count_left的值,记录这个节点左侧搜索元素的数量。这个不难办到:只要在每次新节点插入二叉树的时候,遇到小于等于当前节点值的元素(即insert->val <= root->val),就使root->count_left ++即可。
  2. 同时还有一个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)
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值