Count of Smaller Numbers After Self

315. Count of Smaller Numbers After Self

分析

这道题第一反应用Brute force方法比较直接,两个For Loop解决,时间复杂度是O(n^2),很显然咱们须要用时间复杂度更低的方法。less

方法是在优化第二个For Loop的时候,那么惟一能够想到就是O(logn) 那么咱们就能够考虑用Binary Search Tree来解决。咱们能够经过在建BST的过程当中找到咱们想要的结果。步骤就是从最后一个元素往前开始插入Node, 插入Node的过程当中面对当前Node每次Turn right的时候那么当前点及它全部左子树的节点都表明比待插入点小的元素。为了方便计算,这里的Node咱们增长一个Field表示全部左子树Node及当前Node的总数量,对应在Array里的含义就是包含本身及右边比本身小的元素。oop

代码

class Solution {
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null) return res;        
        Node root = null;
        for (int i = nums.length - 1; i >= 0; i--) {
            root = insert(root, nums[i], 0, res);
        }
        Collections.reverse(res);
        return res;
    }

    public Node insert(Node root, int val, int curr, List<Integer> res) {
        if (root == null) {
            res.add(curr);
            return new Node(val);
        }
        if (val > root.val) {
            root.right = insert(root.right, val, curr + root.lessOrEualCount, res);
        } else {
            root.lessOrEualCount++;
            root.left = insert(root.left, val, curr, res);
        }
        return root;
    }

    class Node {
        Node left, right;
        int val;
        int lessOrEualCount;

        Node(int val) {
            this.val = val;
            lessOrEualCount = 1;
        }
    }
}
相关文章
相关标签/搜索