[英]Where is the flaw in my logic for left-rotating an array N times?
我已经开始了一个小时,无法弄清楚我哪里出错了。 我的实现是
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;
}
}
对于一次旋转,将较低的索引与下一个较高的索引交换,直到到达倒数第二个元素。
while (d-- > 0) {
for(int i=0; i < arr.Length-1; i++) {
swap(i, i+1);
}
小提琴: https : //dotnetfiddle.net/DPkhNw
您正在向左移动,但是您移动了数组中曾经存在的旧值,而不是移动当前循环的元素。
为简单起见,首先确定您的下一个位置,然后使用索引转到原始数组中的该位置(不是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];
}
}
您的逻辑正在向右移动d
个插槽,而不是向左移动。 要向左移动,您希望将索引i+d
的项目复制到索引i
,因此更改
int j = i - d;
到
int j = i + d;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.