给出一个由二维数组表示的矩阵,以及两个正整数 r 和 c,分别表示想要的重构的矩阵的行数和列数java
重构后的矩阵须要将原始矩阵的全部元素以相同的行遍历顺序填充数组
若是具备给定参数的 reshape 操做是可行且合理的,则输出新的重塑矩阵;不然,输出原始矩阵code
示例一以下:io
输入: nums = [[1,2],[3,4]] r = 1, c = 4 输出: [[1,2,3,4]] 解释: 行遍历 nums 的结果是 [1,2,3,4],新的矩阵是 1 * 4 矩阵,用以前的元素值一行一行填充新矩阵
示例二以下:class
输入: nums = [[1,2],[3,4]] r = 2, c = 4 输出: [[1,2],[3,4]] 解释: 没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 因此输出原矩阵
最简单的思路,遍历原数组,将元素放进新数组里边,设置两个标志位防止下标越界重构
class Solution { public int[][] matrixReshape(int[][] nums, int r, int c) { int row = nums.length; int col = nums[0].length; int eleCount = row * col; if(eleCount != r * c) { return nums; } int colFlag = 0; int rowFlag = 0; int[][] newNums = new int[r][c]; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if(colFlag == c) { rowFlag++; colFlag = 0; } newNums[rowFlag][colFlag] = nums[i][j]; colFlag++; } } return newNums; } }
另外一种思路是按照下面的规则直接将元素映射到新数组中遍历
class Solution { public int[][] matrixReshape(int[][] nums, int r, int c) { int m = nums.length; int n = nums[0].length; if (m * n != r * c) { return nums; } int[][] ans = new int[r][c]; for (int x = 0; x < m * n; ++x) { ans[x / c][x % c] = nums[x / n][x % n]; } return ans; } }