繁体   English   中英

如何以相反的顺序将一个数组中最左边的 n 个元素复制到另一个数组中最右边的 n 个位置

[英]How to copy the leftmost n elements in one array into the rightmost n position in another array in reverse order

所以我很难想出一个函数,它接受一个 (int[] X, int n, int[] Y) 作为参数并将 X[] 中最左边的 n 个元素复制到 Y 中最右边的 n 个位置[] 顺序相反。

到目前为止,我已经创建了一个单独的函数来打印出 A 中最左边的 n 个元素的反转。

public static void reverseArray1(int[] A, int n) {
if(n > 0) {
   System.out.print(A[n-1] + " ");
   reverseArray1(A, n-1);
   }
}

这是我目前的程序:

class Recursion {
static void reverseArray1(int[] X, int n, int[] Y) {
//This is where I'm stuck

}

public static void main(String[] args) {
   int[] A = {-1, 2, 3, 12, 9, 2, -5, -2, 8, 5, 7};
   int[] B = new int[A.length];

   for(int x: A) System.out.print(x+" ");
   System.out.println();

   reverseArray1(A, A.length, B);
   for(int x: B) System.out.print(x+" ");
   System.out.println();
   }
}

使用递归这应该非常简单:

void copyNFromLeft(int[] left, int n, int[] right) {
    if (n < 1)
        return;
    right[right.length - n] = left[n - 1];
    copyNFromLeft(left, n - 1, right);
}

您可以为 indexOutOfBounds 情况添加一些额外的检查,例如当n > right.length (或left.length )。 基本上,是这样的:

if (n > left.length || n > right.length)
    n = Math.min(left.length, right.length);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM