Leetcode 315.计算右侧小于当前元素的个数

计算右侧小于当前元素的个数

给定一个整数数组 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 个更小的元素.

 

 

使用BST进行统计。时间复杂度O(nlogn)。

 

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 public class Solution {
 5     TreeNode root;
 6     private int smaller(TreeNode current, int val) {
 7         current.size ++;
 8         if (current.val < val) {
 9             if (current.right == null) current.right = new TreeNode(val);
10             return current.size - 1 - current.right.size + smaller(current.right, val);
11         } else if (current.val > val) {
12             if (current.left == null) current.left = new TreeNode(val);
13             return smaller(current.left, val);
14         } else {
15             return current.left == null? 0 : current.left.size;
16         }
17     }
18     public List<Integer> countSmaller(int[] nums) {
19         List<Integer> result = new ArrayList<>(nums.length);
20         int[] smaller = new int[nums.length];
21         if (nums == null || nums.length == 0) return result;
22         root = new TreeNode(nums[nums.length-1]);
23         for(int i=nums.length-1; i>=0; i--) {
24             smaller[i] = smaller(root, nums[i]);
25         }
26         for(int i=0; i<smaller.length; i++) result.add(smaller[i]);
27         return result;
28     }
29 }
30 class TreeNode {
31     int val;
32     int size;
33     TreeNode left, right;
34     TreeNode(int val) {
35         this.val = val;
36     }
37 }

 

转载于:https://www.cnblogs.com/kexinxin/p/10235176.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值