我左右旋转数组逻辑的缺陷在哪里?

时间:2017-02-02 02:41:05

标签: c# arrays algorithm

我已经开始了一个小时,无法弄清楚我哪里出错了。我的实现是

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是转数。

e.g。 arr=[1,2,3,4]d= 2 - &gt; arr=[3,4,1,2]

4 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

对于一次旋转,使用下一个较高的一个旋转较低的索引,直到到达第二个最后一个元素。

while (d-- > 0) {
    for(int i=0; i < arr.Length-1; i++) {
        swap(i, i+1);
}

小提琴:https://dotnetfiddle.net/DPkhNw

答案 2 :(得分:0)

您向左移动,但是移动了以前存在于数组中的旧值,而不是移动当前的循环元素。

为简单起见,首先确定下一个位置,然后使用索引转到原始数组中的那个位置(不是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];
    }
}

答案 3 :(得分:-1)

您的逻辑正在通过d个广告位移动正确,而不是离开。要转移 left ,您希望将索引i+d中的项目复制到索引i,因此请更改

int j = i - d;

int j = i + d;
相关问题