leetcode算法题答案pdf(LeetCode转置矩阵Java题解)
题目
给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。
矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
代码
public class DayCode {
public static void main(String[] args) {
int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] ans = new DayCode().transpose(matrix);
System.out.println("ans is " Arrays.deepToString(ans));
}
/**
* https://leetcode-cn.com/problems/transpose-matrix/
* 时间复杂度 O (rows * cols)
* 空间复杂度 O (rows * cols)
* @param matrix
* @return
*/
public int[][] transpose(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int[][] ans = new int[cols][rows];
for (int r = 0; r < rows; r ) {
for (int c = 0; c < cols; c ) {
ans[c][r] = matrix[r][c];
}
}
return ans;
}
}
* 理解题意之后,完成代码即可。
,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com