본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 867. Transpose Matrix

반응형

https://leetcode.com/problems/transpose-matrix/description/

 

Transpose Matrix - LeetCode

Can you solve this real interview question? 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. [https://

leetcode.com

📕 풀이방법

📔 입력 및 초기화

matrix의 행을 열로 열을 행으로 2차원 vector 정답 변수 transponsedMatrix를 선언해줍니다.

📔 풀이과정

matrix의 j행 i열 원소를 i행 j열 원소인 transposedMatrix에 저장해줍니다.

📔 정답 출력 | 반환

transposedMatrix을 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& matrix) {
        vector<vector<int>> transposedMatrix(matrix[0].size(), (vector<int>(matrix.size(),0)));
        int row = matrix.size();
        int col = matrix[0].size();
        for(int i = 0; i < col; i++) {
            for(int j = 0; j < row; j++) {
                transposedMatrix[i][j] = matrix[j][i];
            }
        }
        return transposedMatrix;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.