1. 程式人生 > >【LeetCode】566. Reshape the Matrix 解題報告(Python)

【LeetCode】566. Reshape the Matrix 解題報告(Python)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址:https://leetcode.com/problems/reshape-the-matrix/description/

題目描述

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.

Note:

  1. The height and width of the given matrix is in range [1, 100].
  2. The given r and c are all positive.

題目大意

實現Matlab的reshape函式,就是把原來的陣列逐行遍歷重新改成r行,c列,如果不能實現的話就是返回原來的陣列。

解題方法

變長陣列

Python的list是可變的,那麼一個簡單的想法就是使用可變的List作為新的一行,如果新的一行的元素個數等於題目要求的列數,那麼就新建一行。把每行的結果放到返回的列表中即可。

時間複雜度是O(mn),空間複雜度是O(1).沒有額外空間

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        M, N = len(nums), len(nums[0])
        if M * N != r * c:
            return nums
        res = []
        row = []
        for i in range(M):
            for j in range(N):
                row.append(nums[i][j])
                if len(row) == c:
                    res.append(row)
                    row = []
        return res

求餘法

這個做法是由點陣圖法激發出來的,使用一個變數count儲存現在已經有了的元素數量,那麼直接可以使用res[count / c][count % c]確定輪到了的元素的位置。這個方法需要把陣列提前構造好。

時間複雜度是O(mn),空間複雜度是O(1).沒有額外空間

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        M, N = len(nums), len(nums[0])
        if M * N != r * c:
            return nums
        res = [[0] * c for _ in range(r)]
        count = 0
        for i in range(M):
            for j in range(N):
                res[count / c][count % c] = nums[i][j]
                count +=1
        return res

維護行列

上面的方法每次需要通過除法和求餘來確定新的位置,事實上是比較耗時的。更快的方法就是維護行和列的變數,在遍歷的過程中更新行和列,這樣就可以對應放入的位置了。

時間複雜度是O(mn),空間複雜度是O(1).沒有額外空間

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        M, N = len(nums), len(nums[0])
        if M * N != r * c:
            return nums
        res = [[0] * c for _ in range(r)]
        row, col = 0, 0
        for i in range(M):
            for j in range(N):
                if col == c:
                    row += 1
                    col = 0
                res[row][col] = nums[i][j]
                col += 1
        return res

相似題目

參考資料

https://leetcode.com/articles/reshape-the-matrix/

日期

2018 年 11 月 1 日 —— 小光棍節