[LeetCode]566. Reshape the Matrix

題目

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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.

Example 1:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
難度

Easy

方法

轉(zhuǎn)換后的矩陣和之前的矩陣不一樣大時,返回之前的矩陣。否則將之前矩陣的數(shù)據(jù)依次填入新的矩陣中

python代碼
class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        numsRows = len(nums)
        numsCols = len(nums[0])
        if numsRows*numsCols != r*c:
            return nums
        result = [[0 for col in range(c)] for row in xrange(r)]
        i = 0
        while i < r*c:
            result[i/c][i%c] = nums[i/numsCols][i%numsCols]
            i += 1

        return result

assert Solution().matrixReshape([[1,2],[3,4]], 1, 4) == [[1,2,3,4]]
assert Solution().matrixReshape([[1,2],[3,4]], 2, 4) == [[1,2],[3,4]]
assert Solution().matrixReshape([[1,2,3,4]], 2, 2) == [[1,2],[3,4]]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 題目 In MATLAB, there is a very useful function called 'res...
    冷灬葉楓閱讀 269評論 0 0
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,890評論 0 33
  • 題目描述 Reshape the Matrix(重組矩陣) In MATLAB, there is a very ...
    keshiim閱讀 354評論 0 0
  • 今天是9月2日,沒錯,今天就是9月2日,由于昨天9月1日,我返程回學(xué)校以及學(xué)校停水停電導(dǎo)致我沒辦法在9月1日0點前...
    大白兔_X閱讀 207評論 0 1
  • 一顆種子 在石縫中發(fā)芽 每天幾分鐘的陽光 下雨濺入的水滴 它渴望生命 在冷漠中默默生長 看不到外面的花草芬芳 聽不...
    文者字清閱讀 441評論 0 2

友情鏈接更多精彩內(nèi)容