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.
这题看上去一点也不难,就是在元素个数不变,逐行扫描的情况下,改变矩阵的格局。 最简单的方法,就是先得到逐行扫描的结果,变成一个一维矩阵,然后在新的矩阵的在填进去。这就是解法一。 解法二是做了一点点的优化,就是不在有这么一个临时的一维矩阵了,直接根据位置计算的结果往新的矩阵里填东西。
如何构造二维矩阵:
ret := make([][]int, 0)
for i:= 0; i < r; i++ {
ret = append(ret, make([]int, c, c))
}
// 解法一
func matrixReshape(nums [][]int, r int, c int) [][]int {
if nums == nil || len(nums) == r || len(nums)*len(nums[0]) != r*c {
return nums
}
arr := make([]int, r*c, r *c)
row := len(nums)
col := len(nums[0])
for i:= 0; i < row; i++ {
for j := 0; j < col; j++ {
arr[i*col + j] = nums[i][j]
}
}
ret := make([][]int, r, r)
for i := 0; i < r; i++ {
temp := make([]int, c, c)
for j := 0; j < c; j++ {
temp[j] = arr[i*c + j]
}
ret[i] = temp
}
return ret
}
// 解法二
func matrixReshape(nums [][]int, r int, c int) [][]int {
if nums == nil || len(nums) == r || len(nums)*len(nums[0]) != r*c {
return nums
}
ret := make([][]int, 0)
for i:= 0; i < r; i++ {
ret = append(ret, make([]int, c, c))
}
col := len(nums[0])
for i := 0; i < r; i++ {
for j := 0; j < c; j++ {
total := i*c+j
ret[i][j] = nums[total/col][total%col]
}
}
return ret
}