原題連接在這裏:https://leetcode.com/problems/count-of-smaller-numbers-after-self/html
題目:node
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:post
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]
.this
題解:url
從右向左掃描數組nums, 用每一個nums[i]生成TreeNode作BST查找, 返回count 加到 res中.spa
BST當前節點node左側所有是值小於或者等於當前節點node.val的節點,當前結點node.count是左側子樹包括自身的節點總數.code
Time Complexity: O(n^2). BST不必定balance. Space: O(n).htm
AC Java:blog
1 public class Solution { 2 public List<Integer> countSmaller(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 res.add(0); 8 TreeNode root = new TreeNode(nums[nums.length-1]); 9 for(int i = nums.length-2; i>=0; i--){ 10 int curCount = addNode(root, nums[i]); 11 res.add(curCount); 12 } 13 Collections.reverse(res); 14 return res; 15 } 16 17 private int addNode(TreeNode root, int val){ 18 int curCount = 0; 19 while(true){ 20 if(root.val >= val){ 21 root.count++; 22 if(root.left == null){ 23 root.left = new TreeNode(val); 24 break; 25 }else{ 26 root = root.left; 27 } 28 }else{ 29 curCount+=root.count; 30 if(root.right == null){ 31 root.right = new TreeNode(val); 32 break; 33 }else{ 34 root = root.right; 35 } 36 } 37 } 38 return curCount; 39 } 40 } 41 42 class TreeNode{ 43 int val; 44 int count = 1; 45 TreeNode left; 46 TreeNode right; 47 public TreeNode(int val){ 48 this.val = val; 49 } 50 }