Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @author Chaos
- * 566. Reshape the Matrix
- *
- * 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:
- *
- * 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.
- *
- *
- */
- class Solution {
- public int[][] matrixReshape(int[][] nums, int r, int c) {
- if (nums == null) return nums;
- int a = nums.length;
- int b = nums[0].length;
- if (a*b!=r*c) return nums;
- int[][] result = new int[r][c];
- int x=0;
- int y=0;
- for(int i=0; i<a;i++){ // notice there I make a mistake here use r, c instead of a, b
- for(int j=0; j<b;j++){ // should be careful which matrix is actually your mean to loop
- if(x>=c){
- y++;
- x=0;
- }
- result[y][x++]=nums[i][j];
- }
- }
- return result;
- }
- }
Add Comment
Please, Sign In to add comment