Java实现二维数组转置的三种输出方法(IntelliJ IDEA 2017.2.6 x64)
1 import java.util.Arrays; 2 3 /** 4 * Created by Stefango at 9:54 on 2018/7/22 5 */ 6 public class Solution { 7 public static int[][] transpose(int[][] A) { 8 int R = A.length, C = A[0].length; 9 int[][] ans = new int[C][R]; 10 for (int r = 0; r < R; r++) 11 for (int c = 0; c < C; c++) 12 ans[c][r] = A[r][c]; 13 return ans; 14 } 15 16 public static void main(String[] args) { 17 int[][] A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 18 for (int[] i : A) { 19 for (int j : i) 20 System.out.print(j + " "); 21 System.out.println(); 22 } 23 System.out.println("---转置---"); 24 int[][] B = transpose(A); 25 26 // 方法一:传统的for循环 27 // for (int i = 0; i < B.length; i++) { 28 // for (int j = 0; j < B[i].length; j++) 29 // System.out.print(B[i][j] + " "); 30 // System.out.println(); 31 // } 32 33 // 方法二:for each 循环 34 // for (int[] i : B) { 35 // for (int j : i) 36 // System.out.print(j + " "); 37 // System.out.println(); 38 // } 39 40 // 方法三:利用Arrays类中的toString方法(与前两种方法的输出略有不同) 41 for (int i=0;i<B.length;i++) 42 System.out.println(Arrays.toString(B[i])); 43 // 方法三输出为 44 // [1, 4, 7] 45 // [2, 5, 8] 46 // [3, 6, 9] 47 } 48 }
From Stefango