我已经从这里开始一个小时了,但无法弄清楚我哪里出错了。我的实现是
static void LeftRotation(int[] arr, int d)
{
int[] copy = arr.Select(val => val).ToArray();
for(int i = 0; i < arr.Length; ++i)
{
int j = i - d;
arr[i] = j < 0 ? copy[copy.Length + j] : copy[j];
}
}
和d
是旋转的次数。
例如arr=[1,2,3,4]
, d= 2
--> arr=[3,4,1,2]
最佳答案
另一种方式,举个例子:
static void LeftRotation(int[] arr, int d)
{
for (int i = 1; i <= d; i++)
{
//saves the first element
int temp = arr[0];
//moves each element to the left, starting from the 2nd
for (int j = 1; j < arr.Length; ++j)
{
arr[j - 1] = arr[j];
}
//replaces the last elmt with the previously saved first elmt
arr[arr.Length - 1] = temp;
}
}
关于c# - 我将数组向左旋转 N 次的逻辑缺陷在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993363/