Wednesday, May 25, 2016

Count of smaller numbers after self -- Leetcode

Question:
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].
Answer:
Using Binary Indexed Tree(BIT), time: O(N * log N), space: O(1 -- range) array.  Better than naive solution O(N*N). 

public class Solution {
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
       
        Integer min = Integer.MAX_VALUE;
        Integer max = Integer.MIN_VALUE;
        for(int i=0;i<nums.length;++i){
            min = Math.min(min, nums[i]);
            max = Math.max(max, nums[i]);
        }
        int range = max - min + 1;
        int[] tree = new int[range+1];

        for(int i = nums.length - 1; i >= 0; --i){
            int count = getCount(nums[i]-min, tree);
            res.add(0, count);
            addToCount(nums[i]-min+1, tree);
        }
        return res;
    }
   
    public int getCount(int i, int[] tree){
        int count = 0;
        while(i >= 1){
            count += tree[i];
            i -= i & (-i);
        }
        return count;
    }
   
    public void addToCount(int i, int[] tree){
        while(i <= tree.length-1){
            tree[i]++;
            i += i & (-i);
        }
    }
}

No comments:

Post a Comment