Title Link: https://leetcode.com/problems/count-of-smaller-numbers-after-self/
Topic:
you is given an integer array nums and that you had to return a new counts array. The counts array have the property where counts[i"
is the number of smaller elements to the right Of nums[i]
.
Example:
2 1 1 0 smaller element.
Return the array [2, 1, 1, 0]
.
Ideas:
Set up a binary search tree, in the process of building, recorded in the array to the right of the number of elements smaller than itself. Algorithm complexity O (NLOGN), with dynamic programming complexity of O (n^2).
Where CNT is the number of elements of the same size of the node, used for repeating element judgments ... can be omitted in fact. Too lazy to change
Algorithm:
Public list<integer> Countsmaller (int[] nums) {list<integer> List = new arraylist<integer> (); int res[] = new Int[nums.length]; for (int i = nums.length-1; I >= 0; i--) {Res[i] = insert (nums[i]); } for (int i:res) {list.add (i); } return list; } TreeNode Troot; Private Integer Insert (int val) {int cnt = 0; if (troot = = null) {troot = new TreeNode (val); return CNT; } TreeNode root = Troot; while (root = null) {if (Val < root.val) {root.leftcnt++; if (Root.left = = null) {Root.left = new TreeNode (val); Break } else root = Root.left; } else if (val > Root.val) {cnt + = root.leftcnt + root.cnt; if (ROOT.Right = = null) {root.right = new TreeNode (val); Break } else root = Root.right; } else {cnt + = root.leftcnt; root.cnt++; Break }} return CNT; }
"Leetcode" Count of Smaller Numbers after self