C/C++教程

315. Count of Smaller Numbers After Self

本文主要是介绍315. Count of Smaller Numbers After Self,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

数组中每个元素所在位置右边比它小的元素

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;
}
这篇关于315. Count of Smaller Numbers After Self的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!