Leetcode[315] Count of Smaller Numbers After Self

ou 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].

Binary Search Tree

复杂度
O(NlgN), O(N)

思路
每遍历到一个数,就把他insert到已有的BST中。对于每一个node,维护一个leftsum和一个自身的cnt数目。所以对于一个Node来说,比他小的值,应该是每次向右走的时候,就将结果累积到prenum中,其中prenum = node.leftsum + node.cnt

代码

class Node {
    int val;
    int leftSum;
    int cnt;
    Node left;
    Node right;
    public Node(int val) {
        this.val = val;
    }
}


LinkedList<Integer> res;
public List<Integer> countSmaller(int[] nums) {
    res = new LinkedList<>();
    Node root = new Node();
    for(int i = nums.length - 1; i >= 0; i --) {
        helper(nums[i], root, 0);
    }
}

public Node helper(int val, Node root, int preNum) {
    if(root == null) {
        res.addFirst(preNum);
        return new Node(val);
    }
    if(root.val == val) {
        root.cnt ++;
        res.addFirst(preNum + root.leftSum);
    }
    else if(root.val > val) {
        root.leftSum ++;
        root.left = helper(val, root.left, preNum);
    }
    else {
        root.right = helper(val, root.right, preNum + root.leftSum + root.cnt);
    }    
    return root;
}

Binary Index Tree

复杂度
O(NlgN), O(N)

思路
建立一个包含从min到max的数组,[5,2,6,1],然后对于每一个数,考虑从Min到比这个数的小的所有数的和。
比如[1,2,3,4,5,6]=[0,0,0,0,0,0],然后每次遍历到一个数,就把对应位置的值加一。
比如碰到1之后,就变成[1,0,0,0,0,0],然后统计sum[val - 1]的和。

代码

int[] BItree;

public List<Integer> countSmaller(int[] nums) {
    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
    LinkedList<Integer> res = new LinkedList<>();
    if(nums == null || nums.length == 0) return res;
    //
    for(int val : nums) {
        min = Math.min(min, val);
    }
    int diff = 1 - min;
    for(int i = 0; i < nums.length; i ++) {
        nums[i] += diff;
        max = Math.max(max, nums[i]);
    }
    //
    BItree = new int[max + 1];
    for(int i = nums.length - 1; i >= 0; i --) {
        res.addFirst(getSum(nums[i] - 1));
        update(nums[i], BItree.length);
    }
    return res;
}

public int getSum(int index) {
    int res = 0;
    while(index > 0) {
        res += BItree[index];
        index -= index & (-index);
    }
    return res;
}

public void update(int index, int len) {
    while(index < len) {
        BItree[index] ++;
        index += index & (-index);
    }
}

hellolittleJ17
10 声望11 粉丝