题目
在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。 给出一个由二维数组表示的矩阵,以及两个正整数 r 和 c,分别表示想要的重构的矩阵的行数和列数。重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
输入: nums = [[1,2], [3,4]],r = 1, c = 4
输出: [[1,2,3,4]]
解释:行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。
输入: nums =[[1,2], [3,4]],r = 2, c = 4
输出: [[1,2], [3,4]]
解释:没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。
分析
- 给定r 和 c,表示想要重构的矩阵的行数和列数,首先r 和 c得满足:
r * c == nums.length * nums[0].length - 需要获得nums中的元素,然后赋值给一个新数组
法一
设置一个list列表,存储nums中的元素,然后呢根据题目要求,设置新数组,将list中的元素一个个加入数组。这里的list有点像队列。
int[][] ans = new int[r][c];
public int[][] matrixReshape(int[][] nums, int r, int c) {
if (nums.length == 0 || r * c != nums.length * nums[0].length) {
return nums;
}
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
list.add(nums[i][j]);
}
}
int[][] ans = new int[r][c];
for (int i = 0; i < r; i++) {// 决定多少行
for (int j = 0; j < c; j++) {// 决定多少列
ans[i][j] = list.remove(0);
}
}
return ans;
}
法二
遍历nums数组的同时将元素加入新数组,需要用到两个变量,row和col,一个表示行,一个表示列。
当col==c的时候,填充好一行了,让row++,col=0,从下一行的第一个开始继续填充。
// 可以在逐行顺序迭代给定矩阵的同时,直接将数字放在结果矩阵中。
public int[][] matrixReshape2(int[][] nums, int r, int c) {
if (nums.length == 0 || r * c != nums.length * nums[0].length) {
return nums;
}
int[][] ans = new int[r][c];
int row = 0;
int col = 0;
for (int i = 0; i < nums.length; i++) {// 决定多少行
for (int j = 0; j < nums[i].length; j++) {// 决定多少列
ans[row][col++] = nums[i][j];
if (col == c) {
row++;
col = 0;
}
}
}
return ans;
}
法三
提示都已经跟你讲了:
M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices?
Try to use division and modulus to convert 1-d index into 2-d indices.
M[i] => M[n/i][n%i] Will it result in right mapping? Take some example and check this formulae.
提示说:n是数组的列数
public int[][] matrixReshape3(int[][] nums, int r, int c) {
if (nums.length == 0 || r * c != nums.length * nums[0].length) {
return nums;
}
int[][] ans = new int[r][c];
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
ans[count / c][count % c] = nums[i][j];
count++;
}
}
return ans;
}
不是很理解
做题反思
我确实没有读懂提示,但是不用提示也能做出来还是挺好的。
个人喜欢法二。
end.