1 public class Solution { 2 public List<Integer> countSmaller(int[] nums) { 3 List<Integer> res = new ArrayList<>(); 4 if(nums == null || nums.length == 0) return res; 5 TreeNode root = new TreeNode(nums[nums.length - 1]); 6 res.add(0); 7 for(int i = nums.length - 2; i >= 0; i--) { 8 int count = insertNode(root, nums[i]); 9 res.add(count); 10 } 11 Collections.reverse(res); 12 return res; 13 } 14 15 public int insertNode(TreeNode root, int val) { 16 int thisCount = 0; 17 while(true) { 18 if(val <= root.val) { 19 root.count++; 20 if(root.left == null) { 21 root.left = new TreeNode(val); break; 22 } else { 23 root = root.left; 24 } 25 } else { 26 thisCount += root.count; 27 if(root.right == null) { 28 root.right = new TreeNode(val); break; 29 } else { 30 root = root.right; 31 } 32 } 33 } 34 return thisCount; 35 } 36 } 37 38 class TreeNode { 39 TreeNode left; 40 TreeNode right; 41 int val; 42 int count = 1; 43 public TreeNode(int val) { 44 this.val = val; 45 } 46 }
从后向前进行判断,线性的搜索时间复杂度比较高,因此建立一个二叉搜索树,每次插入节点的时候,更新父节点的“右侧小”的数字的数量。