|
| 1 | +# Time: O(m * n) |
| 2 | +# Space: O(m * n) |
| 3 | + |
| 4 | +# In MATLAB, there is a very useful function called 'reshape', |
| 5 | +# which can reshape a matrix into a new one with different size but keep its original data. |
| 6 | +# |
| 7 | +# You're given a matrix represented by a two-dimensional array, |
| 8 | +# and two positive integers r and c representing the row number |
| 9 | +# and column number of the wanted reshaped matrix, respectively. |
| 10 | +# |
| 11 | +# The reshaped matrix need to be filled with |
| 12 | +# all the elements of the original matrix in the same row-traversing order as they were. |
| 13 | +# |
| 14 | +# If the 'reshape' operation with given parameters is possible and legal, |
| 15 | +# output the new reshaped matrix; Otherwise, output the original matrix. |
| 16 | +# |
| 17 | +# Example 1: |
| 18 | +# Input: |
| 19 | +# nums = |
| 20 | +# [[1,2], |
| 21 | +# [3,4]] |
| 22 | +# r = 1, c = 4 |
| 23 | +# Output: |
| 24 | +# [[1,2,3,4]] |
| 25 | +# Explanation: |
| 26 | +# The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, |
| 27 | +# fill it row by row by using the previous list. |
| 28 | +# |
| 29 | +# Example 2: |
| 30 | +# Input: |
| 31 | +# nums = |
| 32 | +# [[1,2], |
| 33 | +# [3,4]] |
| 34 | +# r = 2, c = 4 |
| 35 | +# Output: |
| 36 | +# [[1,2], |
| 37 | +# [3,4]] |
| 38 | +# Explanation: |
| 39 | +# There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. |
| 40 | +# |
| 41 | +# Note: |
| 42 | +# The height and width of the given matrix is in range [1, 100]. |
| 43 | +# The given r and c are all positive. |
| 44 | + |
| 45 | +class Solution(object): |
| 46 | + def matrixReshape(self, nums, r, c): |
| 47 | + """ |
| 48 | + :type nums: List[List[int]] |
| 49 | + :type r: int |
| 50 | + :type c: int |
| 51 | + :rtype: List[List[int]] |
| 52 | + """ |
| 53 | + if not nums or \ |
| 54 | + r*c != len(nums) * len(nums[0]): |
| 55 | + return nums |
| 56 | + |
| 57 | + result = [[0 for _ in xrange(c)] for _ in xrange(r)] |
| 58 | + count = 0 |
| 59 | + for i in xrange(len(nums)): |
| 60 | + for j in xrange(len(nums[0])): |
| 61 | + result[count/c][count%c] = nums[i][j] |
| 62 | + count += 1 |
| 63 | + return result |
0 commit comments