原题链接在这里:https://leetcode.com/problems/count-of-smaller-numbers-after-self/
题目:
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]
.
题解:
从右向左扫描数组nums, 用每个nums[i]生成TreeNode做二叉树查找, 返回count 加到 res中.
二叉树是当前节点node左侧全部是值小于或者等于当前节点node.val的节点,当前结点node.count是左侧子树包括自身的节点总数.
Time Complexity: O(n^2). 二叉树不一定balance. Space: O(n).
AC Java:
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 }
Reference: http://www.cnblogs.com/yrbbest/p/5068550.html