[LeetCode] Transpose Matrix

아르당·2026년 3월 4일

LeetCode

목록 보기
184/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Proble

2차원 정수 배열 행렬이 주어졌을 때, 행렬의 전치를 반환해라.
행렬의 전치행렬은 행렬의 행과 열을 전환하여 대각선으로 뒤집는 것이다.

Eaxmple

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

#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

Solved

class Solution {
    public int[][] transpose(int[][] matrix) {
        int[][] result = new int[matrix[0].length][matrix.length];

        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                result[j][i] = matrix[i][j];
            }
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글