Skip to content

Latest commit

 

History

History
65 lines (55 loc) · 1.39 KB

867. Transpose Matrix.md

File metadata and controls

65 lines (55 loc) · 1.39 KB

leetcode-cn Daily Challenge on Febrary 25th, 2021.


Difficulty : Easy

Related Topics : Array


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.

1

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

Solution

  • 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;
        }