您的当前位置:首页正文

[leetcode: Python]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.

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

方法一:143ms

class Solution(object):
    def matrixReshape(self, nums, r, c):
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        l = []
        for i in nums:
            for j in range(len(i)):
                l.append(i[j]) 
        if r * c != len(l):
            return nums
        k = []
        for i in range(len(l)/c):
            k.append(l[i*c:(i+1)*c])
        return k
            

方法二:112ms

import numpy as np

class Solution(object):
    def matrixReshape(self, nums, r, c):
        return map(list, np.array(nums, dtype=object).reshape(r, c)) if r >= 0 <= c and r * c == sum(map(len, nums)) else nums

class Solution(object):
    def matrixReshape(self, nums, r, c):
        m, n = len(nums), len(nums and nums[0])
        if r * c != m * n or r < 0 or c < 0:
            return nums
        return [[nums[(i*c+j)/n][(i*c+j)%n] for j in xrange(c)] for i in xrange(r)]
        """
        :type nums: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        

因篇幅问题不能全部显示,请点此查看更多更全内容

Top