leetcode - reshape the matrix(java)

silver·2021년 7월 6일
0

level - easy

[문제 내용]
주어진 matrix를 r X c 크기로 변경하여 반환. 단, 변경 불가능할 경우 원래 matrix 반환

[example 1]

Input: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]

[example 2]

Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]

[해결 방법]
새롭게 주어진 매트릭스의 크기가 기존의 매트릭스보다 크거나 작으면,
원래의 매트릭스를 반환하도록 하였다.

새롭게 주어진 매트릭스의 크기가 기존의 매트릭스와 크기가 같다면,
차례대로 값을 설정해주면 된다.

class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        if(r*c != mat.length*mat[0].length) {
            return mat;
        }

        int[][] result = new int[r][c];
        int i = 0, j = 0;
        for(int[] matrix : mat) {
            for(int m : matrix) {
                if(j == c) {
                    j = 0;
                    i++;
                }
                result[i][j++] = m;
            }
        }

        return result;
    }
}

0개의 댓글