c# - 我将数组向左旋转 N 次的逻辑缺陷在哪里?

标签 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是旋转的次数。

例如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/

相关文章:

c# - 无法连接到指定的MySQL主机?

c# - 日期时间变量

c - C中的字符串指针数组

c# - StackExchange.Redis key 按 UTC 日期过期

c - 如何连接指针数组?

使用 glob 排除 index.php 的 PHP 代码

.net - 数据匹配算法

algorithm - 如何快速计算这个系列的模 m 的总和?

Python pandas - 如何对封闭元素进行分组

java - 使用 Math.Floor 比显式整数转换有什么好处吗?