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.
算法分析:就是二维数组与一维数组之间的转换,two[i][j] = one[i * col + j]。其中col是二维数组的列数。C语言版本有两个参数没看懂,所以只做了Python。
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]]
"""
result = []
row = len(nums)
col = len(nums[0])
if row * col != r * c:
return nums
for i in range(r):
temp = []
for j in range(c):
pos = i * c + j
temp.append(nums[pos / col][pos - pos / col * col])
result.append(temp)
return result
巧妙解法
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 r*c != len(nums) * len(nums[0]):
return nums
flat =[]
for i in range(len(nums)):
flat += nums[i]
result =[]
for i in range(r):
result.append(flat[(i*c):(0+i*c + c)])
return result
本文介绍了一种将二维矩阵重塑为特定尺寸的新矩阵的方法,通过行优先遍历的方式保持原有数据不变。提供了两种Python实现方式,包括一般解法和巧妙解法。

286

被折叠的 条评论
为什么被折叠?



