public class Solution { public IList<int> CountSmaller(int[] nums) { if (nums == null || nums.Length == 0){ return new List<int>(); } var result = new List<int>(){0 /*there is no value on the right of last number*/}; var len = nums.Length; var root = new BTNode(nums[len - 1]); for (var i = len - 2; i >= 0; i--){ // add the value of arr on the tree one by one // also update the count of smaller on the 'root' node var smallerCount = BuildAndCount(root, nums[i]); result.Add(smallerCount); } result.Reverse(); return result; } public int BuildAndCount(BTNode current, int value){ int countOfSmaller = 0; while(true){ if(value > current.Value){ // value bigger than current node , add current node's 'count of smaller' on this value countOfSmaller += current.Count + 1; // keep going right ,until reach leaf if(current.Right == null){ current.Right = new BTNode(value); break; }else{ current = current.Right; } } else{ // value is smaller than current node value , increase the count of smaller on current node current.Count ++; // put value on left tree leaf if(current.Left == null){ current.Left = new BTNode(value); break; } else{ current = current.Left; } } } return countOfSmaller; } public class BTNode{ public BTNode Left; public BTNode Right; public int Value; public int Count ; public BTNode (int v){ Value = v; Count = 0; } }}也可以考虑BIT的实现:https://www.topcoder.com/community/data-science/data-science-tutorials/binary-indexed-trees/
新闻热点
疑难解答