[LeetCode]315. Count of Smaller Numbers After Self

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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值