再从萌新开始-Leetcode每日题解-315. Count of Smaller Numbers After Self

315Count of Smaller Numbers After Self(hard)

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


----------------------------------------分割线----------------------------------------------


题目给出一个数组,求出每个元素右边小于它的个数。

分析:

一道BST,从数组尾部开始建树。每个结点除了储存数字(num)和左右孩子结点(left,right)以外,再维护一个变量numOfLeftNode,储存“以当前结点为根结点的子树中,小于等于num的个数(即 左孩子+当前结点 的个数)”


建树时,当插入的数值大于当前结点,递归到右子树,要求结果就可以加上numOfLeftNode了;

当递归到左子树时,当前结点的左孩子数目+1,即numOfLeftNode+1;


代码:

struct Node{       
    int num;       
    int numOfLeftNode;
                   
    Node* left;    
    Node* right;   
                   
    Node(int num,int numOfLeftNode,Node* left=NULL,Node* right=NULL) : num(num),numOfLeftNode(numOfLeftNode),left(left),right(right) {};
                   
};                 


class Solution{      
    public:          
       int insert(Node* tree, int x){
           int ans = 0;      
           bool flag = 0; // 0 for left , 1 for right
        
           while (1){
               
               if ( x > tree->num ){
                   
                   ans += tree->numOfLeftNode;
                   if (tree -> right) tree = tree->right;
                   else {    
                       flag = 1;
                       break;
                   }
                   
               }
               else { 
                   tree->numOfLeftNode++;
        
                   if (tree->left) tree = tree -> left;
                   else break;
               }
           }
        
           Node* tmp = new Node(x,1);
    
           if (!flag) tree->left = tmp;
           else tree->right = tmp;

        
           return ans;
        
       }
    
       vector<int> countSmaller(vector<int>& nums){
           int len = nums.size();
           vector<int> ans(nums.size(),0);
           if (!len) return ans;
  
           Node* head = new Node(nums[len-1],1);
  
           for (int i = nums.size()-2; i >= 0 ; i--)
  
               ans[i] = insert(head,nums[i]);
  
           return ans;
       }

};                                                                                                    


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值