我已经开始了一个小时,不知道我哪里出了问题。我的实现是
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;
}
}
您正在向左移动,但您移动了数组中曾经存在的旧值,而不是移动当前的循环元素。
为简单起见,首先确定下一个位置,然后使用索引转到原始数组中的该位置(不是i
位置),但从复制数组中获取值。
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;
int position = j < 0 ? copy.Length + j : j;
arr[position] = copy[i];
}
}
对于一个旋转,将较低的索引与下一个较高的索引交换,直到到达倒数第二个元素。
while (d-- > 0) {
for(int i=0; i < arr.Length-1; i++) {
swap(i, i+1);
}
小提琴:https://dotnetfiddle.net/DPkhNw
你的逻辑向右移动了d
槽,而不是向左移动。 要向左移动,您希望将索引中的项目复制到索引i+d
i
,因此请更改
int j = i - d;
自
int j = i + d;