数组中每个元素所在位置右边比它小的元素
int[] nums = { 5, 2, 6, 1 }; var rslt = CountSmaller(nums); foreach (var item in rslt) { Console.Write(item + " "); }
private int[] CountSmaller(int[] nums) { if (nums == null || nums.Length == 0) { return new int[] { }; } var tree = new SegmentCountTree(); var numsMap = new Dictionary<int, int>(); var numsArray = new List<int>(); var rslt = new int[nums.Length]; for (int i = 0; i < nums.Length; i++) { numsMap[nums[i]] = nums[i]; } foreach (var item in numsMap) { numsArray.Add(item.Value); } // 若不排序,线段树中的区间会有不合法的 numsArray.Sort(); var minNum = numsArray[0]; tree.Init(numsArray.ToArray(), OperZero); for (int i = nums.Length - 1; i >= 0; i--) { if (nums[i] == minNum) // 未找到 { rslt[i] = 0; tree.UpdateCount(nums[i]); continue; } tree.UpdateCount(nums[i]); // rslt[i] = tree.Query(minNum, nums[i] - 1); } return rslt; } private int OperZero(int arg1, int arg2) { return 0; }