给定一个整数数组 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 个更小的元素.
public class TreeNode{public TreeNode left;public TreeNode right;public int val; //节点值public count = 0;//左子树节点数量}public int[] rightLessNumber(int[] a){int n = a.length;int[] res = new int[n];TreeNode root = null;for(int i = n - 1; i >= 0; i--){//逆序插入二叉搜索树root = insertNode(root, a[i], res, i);}return res;}public TreeNode insertNode(root, val, res, resIndex){if(root == null) root = new TreeNode(val);else if (val <= root.val){root.count += 1;root.left = insertNode(root.left, val, res, resIndex);}else if(val > root.val){res[resIndex] += root.count + 1;root.right = insertNode(root.right, val, res, resIndex);}return root;}
