[转]O(n)数组按给定移位循环旋转的算法
节选出处:CSharpNotesForProfessionals——Section21.1
算法代码:
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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!