題目描述
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.
Example1
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.
Example2
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.
分析
這道題讓我們實現(xiàn)矩陣大小的重塑。
答題思路: 對于這種二維數(shù)組大小重新分配的問題的關(guān)鍵就是對應(yīng)位置的坐標(biāo)轉(zhuǎn)換,最直接的辦法就是把原數(shù)組拉直胸梆,變成一條直線念恍,然后再組成新數(shù)組话原。
解法1
這道題我們先判斷給定數(shù)組是否能重塑成給定的大小绍豁,就是看兩者的元素個數(shù)是否相同,直接行數(shù)乘以列數(shù)即可通贞,然后我們重建一個目標(biāo)大小的數(shù)組焊夸,并開始遍歷仁连,對于每個位置,我們先轉(zhuǎn)為拉之后的一維坐標(biāo)阱穗,然后在算出在原數(shù)組中的對應(yīng)位置復(fù)制過來即可饭冬,代碼如下:
C++
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int m = nums.size(), n = nums[0].size();
if (m * n != r * c) return nums;
vector<vector<int>> res(r, vector<int>(c));
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int k = i * c + j;
res[i][j] = nums[k / n][k % n];
}
}
return res;
}
};
Swift
func matrixReshape(_ nums: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
let m = nums.count, n = nums[0].count
if (m * n != r * c) { return nums }
var res = [[Int]](repeating: [Int](repeating: 0, count: c), count: r)
for i in 0..<r {
for j in 0..<c {
let k = i * c + j
res[i][j] = nums[k / n][k % n]
}
}
return res
}
print(matrixReshape([[1, 2], [3, 4]], 1, 4))
解法2
下面這種方法整體思路和上面沒啥區(qū)別,但是只使用了一個循環(huán)揪阶,直接就是遍歷拉直后的一維數(shù)組的坐標(biāo)昌抠,然后分別轉(zhuǎn)換為兩個二維數(shù)組的坐標(biāo)進行賦值,參見代碼如下:
C++
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int m = nums.size(), n = nums[0].size();
if (m * n != r * c) return nums;
vector<vector<int>> res(r, vector<int>(c));
for (int i = 0; i < r * c; i++) {
res[i / c][i % c] = nums[i / n][i % n];
}
return res;
}
};
Swift
func matrixReshape(_ nums: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
let m = nums.count, n = nums[0].count
if (m * n != r * c) { return nums }
var res = [[Int]](repeating: [Int](repeating: 0, count: c), count: r)
for i in 0..<r*c {
res[i / c][i % c] = nums[i / n][i % n]
}
return res
}
print(matrixReshape([[1, 2], [3, 4]], 1, 4))