【LeetCode】867. Transpose Matrix 转置矩阵(Easy)(JAVA)

【LeetCode】867. Transpose Matrix 转置矩阵(Easy)(JAVA)

题目地址: https://leetcode.com/problems/transpose-matrix/

题目描述:

Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix’s row and column indices.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2:

Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 10^5
  • -10^9 <= matrix[i][j] <= 10^9

题目大意

给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。

矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

解题方法

  1. 遍历二维数组,然后交换行和列的位置即可
class Solution {
    public int[][] transpose(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return matrix;
        int[][] res = new int[matrix[0].length][matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                res[j][i] = matrix[i][j];
            }
        }
        return res;
    }
}

执行耗时:1 ms,击败了38.35% 的Java用户
内存消耗:39.4 MB,击败了43.95% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/114058610