2016-04-04 29 views
-1

因此,我試圖想出一個函數來接受(int [] X,int n, int [] Y)作爲參數,並將Y []中最左邊的n個元素以相反順序複製到最右邊的n個位置。如何將一個數組中最左邊的n個元素按相反順序複製到另一個數組中最右邊的n位

到目前爲止,我已經創建了一個單獨的函數,打印出最左邊的N元素的A.逆轉

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(); 
    } 
} 
+1

歡迎來到SO。你可以多加一點,比如寫一個測試方法,用[1,2,3,4]的int數組調用reverseArray1,n是3?也許打印結果並說出你的預期? – rajah9

回答

0

這應該很簡單,使用遞歸:

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

您可以添加一些額外的檢查indexOutOfBou例如,當n > right.length(或left.length)。基本上,這樣的事情:

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

謝謝。你讓我放心,我正走在正確的軌道上! – HPotter

+0

@HPotter沒有問題,如果答案幫助您解決了您的問題,請考慮將其標記爲**已接受**,以清楚說明您的*問題已回答*,謝謝 – radoh

相關問題