【问题标题】:How to copy the leftmost n elements in one array into the rightmost n position in another array in reverse order如何以相反的顺序将一个数组中最左边的n个元素复制到另一个数组中最右边的n个位置
【发布时间】:2016-07-24 14:47:26
【问题描述】:

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

到目前为止,我已经创建了一个单独的函数,可以打印出 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();
   }
}

【问题讨论】:

  • 欢迎来到 SO。你能再补充一点吗,比如写一个测试方法来调用 reverseArray1 用一个 [1, 2, 3, 4] 的 int 数组和一个 3 的 n?也许打印结果并说出您的期望?

标签: java arrays recursion data-structures


【解决方案1】:

使用递归应该很简单:

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 &gt; right.length(或left.length)。基本上是这样的:

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

【讨论】:

  • 谢谢。你刚刚向我保证我是在正确的轨道上!
  • @HPotter 没问题,如果某个答案帮助您解决了问题,请考虑将其标记为已接受,以表明您的问题已得到回答 ,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2019-12-16
  • 2020-08-09
  • 2011-03-31
相关资源
最近更新 更多