Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Return the array [2, 1, 1, 0].

Solution:

public class Solution {
    class Node {
        int val, num, dup=1;
        Node left, right;
        public Node(int v, int n){ val = v; num = n; }
    }
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> ans = new LinkedList<>();
        if(nums.length==0) return ans;
        Node root = null;
        for(int i=nums.length-1; i>=0; i--) root = insert(root, nums[i], ans, 0);
        return ans;
    }
    public Node insert(Node root, int val, List<Integer> ans, int pre){
        if(root==null) {
            root = new Node(val, 0);
            ans.add(0, pre);
        } else if(val==root.val){
            root.dup++;
            ans.add(0, pre+root.num);
        } else if(val<root.val){
            root.num++;
            root.left = insert(root.left, val, ans, pre);
        } else {
            root.right = insert(root.right, val, ans, pre+root.dup+root.num);
        }
        return root;
    }
}
comments powered by Disqus