java 数组旋转 n 个元素在测试中给出了错误的输出

java array rotating by n element gives wrong output in test

我在尝试解决这个问题时遇到了问题。这是任务:

编写一个程序,使列表旋转多次(第一个元素变为最后一个)。

list = 1,2,3,4,5 and N = 2 -> result = 3,4,5,1,2

请注意,N 可能大于列表的长度,在这种情况下,您将多次旋转列表。

list = 1,2,3,4,5 and N = 6 -> result = 2,3,4,5,1

输入 在第一行,您将收到号码列表。 在第二行你会收到 N

输出 在唯一的输出行上,打印由 space.

分隔的数字

这是测试:

TEST 1:

Input 5,3,2,1 2

Output 2,1,5,3

TEST 2:

Input 2,1,3,4 5

Output 1,3,4,2

到目前为止,这是我的代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();

        String[] elements = input.split(",");
        int[] array = new int[elements.length];

        for (int i = 0; i < elements.length; i++) {
            array[i] = Integer.parseInt(elements[i]);
        }

        int a = scanner.nextInt();


        int[] rotated = new int[elements.length];


        for (int x = 0; x <= array.length - 1; x++) {
            rotated[(x + a) % array.length] = array[x];
        }


        for (int i = 0; i < rotated.length; i++) {

            if (i > 0) {
                System.out.print(",");
            }
            System.out.print(rotated[i]);


        }
    }
}

第一个测试通过。但是第二个测试没有通过,我的程序给了我错误的输出:4,2,1,3 而不是正确的输出:1,3,4,2.

我想不通是哪里出了问题

提前感谢您的帮助。

您的逻辑可以简化为:

public static void shiftLeft(int shiftBy, int arr[]) {
    for (int j = 0; j < shiftBy; j++) {
        int a = arr[0];                         // storing the first index
        int i;
        for (i = 0; i < arr.length - 1; i++) {  // shifting the array left
            arr[i] = arr[i + 1];
        }
        arr[i] = a;                             // placing first index at the end
    }
}

现在称呼它:

public static void main(String[] args) {
    //  Fetch all data from user as you have done

    int arr[] = { 1, 2, 3, 4, 5 };
    shiftLeft(n % arr.length, arr);

    // print out the array
}

请注意,如果数字 n 大于数组的 长度 ,则实际上不必将其移动那么多次。相反,你只需要移动它 n % arr.length 次。