数组旋转问题 - 无法获得所需的输出

Array rotation problem - not able to get desired output

我写了一个代码来将大小为 n 的数组旋转 d 个元素。我使用临时数组来解决问题。但是我变得不同 output.There 是我的代码中的语法错误。谁能帮我? 代码:

public static void rotate(int a[], int d, int n) {
    int temp[] = new int[n];
    for (int i = d; i < a.length; i++) {
        for (int j = 0; j < n - 2; j++) {
            temp[j] = a[i];
        }
    }
    for (int i = 0; i < d; i++) {
        for (int j = n - 2; j < temp.length; j++) {
            temp[j] = a[i];
        }
    }
    System.out.println("result is");
    for (int k = 0; k < temp.length; k++) {
        System.out.println(temp[k]);
    }
}
public static void main(String[] args) {
    int size, d;
    Scanner sc = new Scanner(System.in);
    System.out.println("enter size");
    size = sc.nextInt();
    System.out.println("enter rotate count");
    d = sc.nextInt();
    int a[] = new int[size];
    for (int i = 0; i < size; i++) {
        a[i] = sc.nextInt();
    }
    rotate(a, d, size);
}

输入:

enter size 7

enter rotate count 2

input array a[]=1 2 3 4 5 6 7

我得到的输出:

7 7 7 7 7 2 2

预期输出:

3 4 5 6 7 1 2

你的逻辑不正确,你不应该在任何地方有双循环,它们会破坏一切,绝对没有理由让它们合乎逻辑。

for(int i=d;i<a.length;i++){
    for(int j=0;j<n-2;j++){
        temp[j]=a[i];
    }
}

这样做的目的是 temp 中的每个元素都将具有 a[a.length - 1] 的值。外循环的所有迭代都将被外循环的最后一次迭代完全覆盖,此时 i 将为 a.length - 1,然后迭代大部分 temp 并覆盖所有它们a[a.length - 1] 的值。您误用了 ij 并且 -2 应该是 -d 如果有的话。

通常有两种方法可以做到这一点:手动将索引环绕数组边界或使用模运算符为您进行环绕。使用模数是更简洁的方法,因此我将展示一个:

public static void rotate(int a[], int rotate){
    int temp[]=new int[a.length];
    for (int i = 0; i < a.length; i++) {
        temp[i] = a[(i + rotate) % a.length];
    }
    
    System.out.println("result is");
    for (int k = 0; k < temp.length; k++){
        System.out.println(temp[k]);
    }
}

然后您通过 rotate(a,d);

调用

您可以使用一个 for 循环 和一个 if 语句 来简化您的代码。将元素移到数组的开头,将元素移到数组末尾:

public static void rotate(int[] arr, int d) {
    int[] temp = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        if (i < arr.length - d) {
            // shift the far elements to
            // the beginning of the array
            temp[i] = arr[i + d];
        } else {
            // shift the near elements
            // to the end of the array:
            temp[i] = arr[i + d - arr.length];
        }
    }
    // replace the contents of the array
    // with the contents of the temp array
    System.arraycopy(temp, 0, arr, 0, arr.length);
}
public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6, 7};
    rotate(arr, 2);
    System.out.println(Arrays.toString(arr));
    // [3, 4, 5, 6, 7, 1, 2]
}

另请参阅: