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]]code
public int[][] matrixReshape(int[][] nums, int r, int c) { if(nums == null || nums.length == 0 || r*c != nums.length*nums[0].length) return nums; int heightIndex = 0; int widthIndex = 0; //保存結果數組 int[][] res = new int[r][c]; for(int i =0;i<nums.length;i++){ for(int j=0;j<nums[0].length;j++){ res[heightIndex][widthIndex] = nums[i][j]; widthIndex ++; if(widthIndex == c){ heightIndex ++; widthIndex = 0; } } } return res; }