The original title link is here: https://leetcode.com/problems/count-of-smaller-numbers-after-self/
Topic:
You were given an integer array nums and you had to return a new counts array. The counts array has the property where are the number of smaller elements to the right of counts[i]
nums[i]
.
Example:
nums = [5, 2, 6, 1]to the right of 5 there is 2 smaller elements (2 and 1). The right of 2 there are only 1 smaller element (1). The right of 6 there is 1 smaller element (1). The right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0]
.
Exercises
Scan array nums from right to left, use each nums[i] to generate TreeNode to do binary tree lookup, return count plus to res.
The binary tree is the node on the left side of the node where the value is less than or equal to the current node node.val, and the node Node.count is the total number of nodes on the left subtree including itself.
Time Complexity:o (n^2). A binary tree is not necessarily balance. Space:o (n).
AC Java:
1 Public classSolution {2 PublicList<integer> Countsmaller (int[] nums) {3list<integer> res =NewArraylist<integer>();4 if(Nums = =NULL|| Nums.length = = 0){5 returnRes;6 }7Res.add (0);8TreeNode root =NewTreeNode (nums[nums.length-1]);9 for(inti = nums.length-2; i>=0; i--){Ten intCurcount =AddNode (Root, nums[i]); One Res.add (curcount); A } - Collections.reverse (res); - returnRes; the } - - Private intAddNode (TreeNode root,intval) { - intCurcount = 0; + while(true){ - if(Root.val >=val) { +root.count++; A if(Root.left = =NULL){ atRoot.left =NewTreeNode (val); - Break; -}Else{ -Root =Root.left; - } -}Else{ incurcount+=Root.count; - if(Root.right = =NULL){ toRoot.right =NewTreeNode (val); + Break; -}Else{ theRoot =Root.right; * } $ }Panax Notoginseng } - returnCurcount; the } + } A the classtreenode{ + intVal; - intCount = 1; $ TreeNode left; $ TreeNode right; - PublicTreeNode (intval) { - This. val =Val; the } -}
Reference:http://www.cnblogs.com/yrbbest/p/5068550.html
Leetcode Count of Smaller Numbers after self