【LeetCode】867. Transpose Matrix (Easy) (JAVA)
Subject address: https://leetcode.com/problems/transpose-matrix/
Title description:
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
General idea
Gives you a two-dimensional integer array matrix, and returns the transposed matrix of the matrix.
The transposition of a matrix refers to flipping the main diagonal of the matrix and exchanging the row index and column index of the matrix.
Problem-solving method
- Traverse the two-dimensional array, and then swap the row and column positions
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;
}
}
Execution time: 1 ms, beating 38.35% of Java users
Memory consumption: 39.4 MB, beating 43.95% of Java users