Guest User

Untitled

a guest
Mar 18th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. /**
  2. * @author Chaos
  3. * 566. Reshape the Matrix
  4. *
  5. * In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into
  6. * a new one with different size but keep its original data.
  7. * You're given a matrix represented by a two-dimensional array, and two positive integers r
  8. * and c representing the row number and column number of the wanted reshaped matrix, respectively.
  9. * The reshaped matrix need to be filled with all the elements of the original matrix in the same
  10. * row-traversing order as they were.
  11. * If the 'reshape' operation with given parameters is possible and legal, output the new reshaped
  12. * matrix; Otherwise, output the original matrix.
  13. *
  14. * Example:
  15. *
  16. * Input:
  17. * nums =
  18. * [[1,2],
  19. * [3,4]]
  20. * r = 1, c = 4
  21. * Output:
  22. * [[1,2,3,4]]
  23. * Explanation:
  24. * The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row
  25. * by row by using the previous list.
  26. *
  27. *
  28. */
  29.  
  30.  
  31. class Solution {
  32. public int[][] matrixReshape(int[][] nums, int r, int c) {
  33. if (nums == null) return nums;
  34.  
  35. int a = nums.length;
  36. int b = nums[0].length;
  37.  
  38. if (a*b!=r*c) return nums;
  39. int[][] result = new int[r][c];
  40. int x=0;
  41. int y=0;
  42. for(int i=0; i<a;i++){ // notice there I make a mistake here use r, c instead of a, b
  43. for(int j=0; j<b;j++){ // should be careful which matrix is actually your mean to loop
  44. if(x>=c){
  45. y++;
  46. x=0;
  47. }
  48. result[y][x++]=nums[i][j];
  49. }
  50. }
  51. return result;
  52. }
  53.  
  54. }
Add Comment
Please, Sign In to add comment