矩阵转置
矩阵转置,很复杂嘛?为嘛我跟面试官说对于m×n的矩阵,定义一个n×m的矩阵,然后逐行拷贝新矩阵的列就搞定,有问题?有问题?为啥要问那么多次?
package hangxin; public class Juzhenzhuanzhi { public static int[][] matrixTranspose(int[][] arr) { int[][] arrResult = new int[arr[0].length][arr.length]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { arrResult[j][i] = arr[i][j]; } } return arrResult; } public static void print(int[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print( arr[i][j] + " "); } System.out.println(""); } System.out.println(""); } public static void main(String[] args) { int[][] arr = {{1, 2, 3},{ 4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; print(arr); int[][] arr2 = matrixTranspose(arr); print(arr2); } }