题意
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.
题意
这道题就是希望模拟MATLAB中对软件进行变形,变成指定行列的新矩阵
想法
其实这个解法也是很简单的模拟,使用一个暂存列表来保存新行元素,通过判断是不是达到指定列长来决定是不是加到结果列表中。而且比较友好的是它给定的是二维数组,如果是多维的话,我可能会考虑用递归去遍历得到元素,但比较痛苦的便是最后你要组成元素了。。。可以当成升级版来想
然后我反思一下简单版里我的做法,我的做法一开始还用了if-else来判断是不是生成了足够的元素,但后来交完后看到这个做法是不够简洁的,其实只用一个if判断列表生成足够元素后加进结果集就可以了,反思一下。还有一种比较简洁的做法就是从行的角度来考虑,以行r为遍历下标,每次取r*c到(r+1)*c的元素填充进去,这个用到了列表的slicing和extend,就比较简洁,连判断也不用了。
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if (len(nums)==r and len(nums[0])==c) or (len(nums)*len(nums[0])!=r*c):
return nums
result = list()
# tmp = list()
# cnt = 0
# for i in range(len(nums)):
# for j in range(len(nums[i])):
# tmp.append(nums[i][j])
# cnt += 1
# if cnt == c:
# result.append(tmp)
# tmp = list()
# cnt = 0
# return result
num1 = list()
for i in range(len(nums)):
num1.extend(nums[i])
for time in range(r):
result.append(num1[time*c: (time+1)*c])
return result