leetcode-cn Daily Challenge on Febrary 25th, 2021.
Difficulty : Easy
Related Topics : Array
Given a 2D integer array
matrix
, return the transpose ofmatrix
.The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]
Input: matrix = [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 10^5
-10^9 <= matrix[i][j] <= 10^9
- mine
- Java
Runtime: 0 ms, faster than 100.00%, Memory Usage: 39.9 MB, less than 52.14% of Java online submissions
// O(R * C)time // O(R * C)space public int[][] transpose(int[][] matrix) { int r = matrix.length; int c = matrix[0].length; int[][] res = new int[c][r]; for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ res[j][i] = matrix[i][j]; } } return res; }
- Java