본문 바로가기

Algorithm/Leetcode

[Leetcode] Reshape the Matrix (#566)

 

 

문제 

 

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.

 

 

 

코드 
class Solution(object):
    def matrixReshape(self, mat, r, c):
        answer = sum(mat, [])
        arr = []
        if len(answer) == r * c:
            for i in range(0,len(answer),c):
                num = answer[i:i+c]
                arr.append(num)
            return arr
        else:
            return mat
분석 > 이 문제는 어렵지 않았지만 2차원 배열을 1차원 배열로 바꾸는 법을 새롭게 알게 되었던 문제이다. sum(배열, []) 을 꼭 기억해 두자. 

 

 

 

 

Reshape the Matrix - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com