본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 566. Reshape the Matrix

반응형

https://leetcode.com/problems/reshape-the-matrix/description/

 

Reshape the Matrix - LeetCode

Can you solve this real interview question? Reshape the Matrix - In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data. You are given an m x n matrix mat a

leetcode.com

2차원 vector를 다루는 구현 문제였습니다.

📕 풀이방법

📔 풀이과정

1. valid한 경우는 matrix의 원소 개수가 r*c와 같은 경우입니다. 방 개수만큼 원소를 가지고 있어야하기 때문에 이렇게 입력이 주어지지 않았다면 원본 mat을 반환합니다.2. mat의 원소를 담을 일차원 vector nums를 선언해줍니다.3. 정답 vector ans는 2차원으로 r행 c열만큼의 방을 가지도록 선언해줍니다.4. r X c만큼 2차원 for loop를 수행하며 nums의 i*c+j번째 원소를 ans i행 j열에 옮겨줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        if(mat.size() * mat[0].size() != r*c) return mat;
        vector <int> nums;
        vector<vector<int>> ans(r, vector<int>(c));
        for(auto i : mat) {
            for(auto j : i) {
                nums.push_back(j);
            }
        }
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                ans[i][j] = nums[i*c+j];
            }
        }
        return ans;
    }
};

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