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