PS/LeetCode

[LeetCode] Reshape the Matrix (JAVA)

제이온 (Jayon) 2021. 11. 8.

문제

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 and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

 

입출력 및 제약 사항

 

풀이

나머지 연산을 이용한 배열 구현 문제였습니다. 또한, 주의할 점은 기존 배열의 가로, 세로를 곱한 값과 주어진 r과 c를 곱한 값이 다르면 기존 배열을 그대로 반환해야 했습니다. 처음에 문제를 대충 읽는 바람에 2번째 예제가 무슨 말인지 헤맸습니다.

 

기존 배열 m * n을 r * c 형태로 만드는 방법은 간단합니다. 기존 배열을 mat, 변경된 배열을 answer라고 한다면 다음과 같이 한 줄의 수식으로 끝이 납니다.

 

answer[i / c][i % c] = mat[i / n][i % n] (단, i는 0 <= i < r * c 범위를 갖는다.)

 

예를 들어, mat가 {{1, 2}, {3, 4}, {5, 6}, {7, 8}} 이고, r = 2, c = 4라고 가정해 봅시다. 위 수식에 의하면, 다음과 같이 배열이 채워 집니다.

 

answer[0][0] = mat[0][0] = 1

answer[0][1] = mat[0][1] = 2

answer[0][2] = mat[1][0] = 3

answer[0][3] = mat[1][1] = 4

answer[1][0] = mat[2][0] = 5

answer[1][1] = mat[2][1] = 6

answer[1][2] = mat[3][0] = 7

answer[1][3] = mat[3][1] = 8

 

아래는 위 과정을 정리한 소스 코드입니다.

 

소스코드

class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        if (mat.length * mat[0].length != r * c) {
            return mat;
        }
        
        int[][] answer = new int[r][c];
        for (int i = 0; i < r * c; i++) {
            answer[i / c][i % c] = mat[i / mat[0].length][i % mat[0].length];
        }
        return answer;
    }
}

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] Backspace String Compare (JAVA)  (0) 2021.11.10
[LeetCode] Add Binary (JAVA)  (0) 2021.11.02
[LeetCode] Move Zeroes (JAVA)  (0) 2021.10.20
[LeetCode] Squares of a Sorted Array (JAVA)  (0) 2021.10.19
[LeetCode] Rotate Array (JAVA)  (0) 2021.10.19

댓글

추천 글