https://leetcode.com/problems/count-of-smaller-numbers-after-self/?tab=Description
找出后面有多少个数比当前值小
线段树变形,从后向前遍历,注意看node内要存什么
public class Solution {
public List<Integer> countSmaller(int[] nums) {
if (nums == null || nums.length == 0) {
return new LinkedList();
}
TreeNode root = null;
Integer[] ans = new Integer[nums.length];
for (int i = nums.length - 1; i >= 0; i--) {
root = insert(nums, i, 0, root, ans);
}
return Arrays.asList(ans);
}
private TreeNode insert(int[] nums, int index, int preSum, TreeNode root, Integer[] ans) {
if (root == null) {
ans[index] = preSum;
root = new TreeNode(nums[index]);
} else if (root.val == nums[index]) {
ans[index] = preSum + root.count;
root.dup++;
} else if (root.val > nums[index]) {
root.count++;
root.left = insert(nums, index, preSum, root.left, ans);
} else if (root.val < nums[index]) {
root.right = insert(nums, index, preSum + root.count + root.dup, root.right, ans);
}
return root;
}
}
class TreeNode {
// 当前node的val
int val;
// 比当前val小的数字个数
int count;
// 等于当前val的数字个数,最开始就有一个!!!
int dup;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
dup = 1;
}
}