2014-11-22 92 views
0

我想用java中的遞歸打印數組,但唯一的參數是數組本身。可能嗎?在java中使用遞歸打印數組

public static void printintArr(int[] a) 
+0

是的,只要您可以將當前索引存儲爲字段即可。不建議這樣做 - 將當前索引作爲參數傳遞更加簡潔。 – 2014-11-22 11:54:28

+0

你也可以打印第一個元素,創建另一個包含所有其他元素的數組,並用這個「子數組」遞歸地調用你的方法。這當然是一個愚蠢的解決方案,但要求也是愚蠢的。 – 2014-11-22 12:03:20

+0

@JBNizet我想這也是「我的CPU能力太強了,我該如何在'O(n^2)'?中打印數組」。儘管有趣,但這是解決方案。 – 2014-11-22 12:10:08

回答

1

這是可能的。這是做這件事:

public static void print(int[] array) { 
    if (array == null || array.length == 0) { 
     return; 
    } else { 
     System.out.println(array[0]); 
     int[] next = new int[array.length - 1]; 
     System.arraycopy(array, 1, next, 0, array.length - 1); 
     print(next); 
    } 
} 
0

從結束:

void printer(int[] input){ 
    if(input.length > 0){ 
     System.out.println(input[input.length-1]); 
     printer(Arrays.copyOf(input, input.length-1)); 
    } 
} 

從開始:

void printer(int[] input){ 
    if(input.length > 0){ 
     System.out.println(input[0]); 
     printer(Arrays.copyOfRange(input, 1, input.length)); 
    } 
} 
+0

如果輸入。長度== 0這將拋出ArrayIndexOutOfBoundException – macias 2014-11-22 12:05:34

+0

@macias現在可以工作嗎? – 2014-11-22 12:07:57

+0

是的,我猜...;) – macias 2014-11-22 12:09:29

1
public static void main(String[] args) { 
    int[] array = new int[] {1, 2, 3, 4, 5}; 
    printArr(array); 
} 

public static void printArr(int[] a) { 
    if (a != null && a.length > 0) { 
     System.out.println(a[0]); 
     // Call the function printArr with the full array, without the first element 
     printArr(Arrays.copyOfRange(a, 1, a.length)); 
    } 
} 

你必須導入java.util.Arrays中

輸出:

1 
2 
3 
4 
5 
0

到目前爲止,這裏的其他解決方案都涉及到重複複製整個數組減去一個元素。這是非常緩慢的。他們運行在O(n )時間。

有一種方式O(n)的時間,但有List做到這一點:

public void print(final List<?> list) { 
    if (list.isEmpty()) { 
     return; 
    } 
    System.out.println(list.get(0)); 
    print(list.subList(1, list.size())); 
} 

因爲subList視圖而不是副本,這種方法將運行在O(n)時間,你所期望的。可悲的是需要一個List而不是一個數組。

幸運的是,有一個很簡單的方法來得到一個Object陣列成List

final String[] data = {"a", "b", "c", "d"}; 
List<String> list = Arrays.asList(data); 

這並不陣列複製,它只是返回數組作爲List的視圖。遺憾的是,這對原始數組不起作用。對於你需要做的是這樣的:

final int[] data = {1, 2, 3, 4}; 
Arrays.stream(data).boxed().collect(toList()); 

這確實需要一個副本。

我想指出,雖然,一個O(n)的複製後跟爲O(n)打印仍然會比單個爲O(n )操作更有效率。