Two java solution with thinking process


  • 0

    Straightforward solution:

    Use two pair of index (x, y) and (i, j) to assign values of nums to new matrix. Be careful with the boundaries.

    public class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            int row = nums.length;
            int col = nums[0].length;
            if(r*c != row*col) return nums;
            
            int x=0, y=0;
            int[][] newMatrix = new int[r][c];
            for(int i=0; i<r; ++i){
                for(int j=0; j<c; ++j){
                    if(y==col){
                        x++;
                        y=0;
                    }
                    newMatrix[i][j] = nums[x][y++];
                }
            }
            
            return newMatrix;
        }
    }
    

    Advanced solution:

    Suppose we have an array of integers nums and we want to put them in any r*c matrix. How to find the corresponding position for the nums[n]?

    Simple:
    row = n/c
    col = n%c
    So
    nums[n] = matrix[n/c][n%c]

    Now let's say we have two matrixes and an array.
    For any number in the array:
    nums[n] = matrix1[n/c1][n%c1] = matrix2[n/c2][n%c2]

    Let's ignore this imaginary array.

    public int[][] matrixReshape(int[][] nums, int r, int c) {
            int row = nums.length;
            int col = nums[0].length;
            if(r*c != row*col) return nums;
            
            int[][] newMatrix = new int[r][c];
            for(int i=0; i<r*c; ++i){
                newMatrix[i/c][i%c] = nums[i/col][i%col];
            }
            
            return newMatrix;
        }
    

  • 0
    H

    Hi UpTheHell, thanks for sharing. May I know the run time of your two solution?


  • 0
    2

    @hansensen

    Hint: both solutions have the same runtime


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.