VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • [转]O(n)数组按给定移位循环旋转的算法

算法代码:

private static void Rotate<T>(ref T[] array, int shiftCount)
{
	T[] backupArray= new T[array.Length];
	for (int index = 0; index < array.Length; index++)
	{
		backupArray[(index + array.Length + shiftCount % array.Length) % array.Length] = array[index];
	}
	array = backupArray;
}

算法示例:

public static void Main()
{
	int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	int shiftCount = 1;
	Rotate(ref array, shiftCount);
	Console.WriteLine(string.Join(", ", array));
	// Output: [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
	array = new []{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	shiftCount = 15;
	Rotate(ref array, shiftCount);
	Console.WriteLine(string.Join(", ", array));
	// Output: [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
	array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	shiftCount = -1;
	Rotate(ref array, shiftCount);
	Console.WriteLine(string.Join(", ", array));
	// Output: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
	array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	shiftCount = -35;
	Rotate(ref array, shiftCount);
	Console.WriteLine(string.Join(", ", array));
	// Output: [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
}

核心公式:(index + array.Length + shiftCount % array.Length) % array.Length
这段代码中重要的是公式,旋转后我们用它来查找新的索引值。

  • (shiftCount % array.Length) -> 我们将移位值规范化在数组的长度内(因为在长度为10的数组中,移位1或11是相同的事情,-1和-11也是一样的)。

  • array.Length + (shiftCount % array.Length) -> 这样做是由于向左旋转,以确保我们不会进入负索引,而是将其旋转到数组的末尾。 如果没有它,则索引0的长度为10且旋转为-1的数组将变为负数(-1),而不会获得实际的旋转索引值,即9。(10 +(-1%10)= 9)

  • index + array.Length + (shiftCount % array.Length) -> 在此不多说,因为我们将旋转应用于索引以获取新索引。 (0 + 10 +(-1%10)= 9)

  • (index + array.Length + (shiftCount % array.Length) ) % array.Length -> 第二个规范化操作是确保新索引值不会超出数组的范围,而是在数组的开头旋转该值。 它用于右旋转,因为在长度为10的数组中没有索引9和旋转1的数组,我们将进入数组之外的索引10,而没有得到真实的旋转索引值为0。(((9 + 10 +(1%10))%10 = 0)

    出处:https://goalkicker.com/CSharpBook/


相关教程