My Java Solution beats 93% 7ms


  • 0
    R
    public int[][] matrixReshape(int[][] nums, int r, int c) {
            int[][] reshapedMatrix = new int[r][c];
            int rows = nums.length, cols = nums[0].length;
            if(rows*cols == r*c){
                int rowUpdated = 0, colUpdated = 0;
                for(int i = 0; i < rows; i++){
                    for(int j = 0; j < cols; j++){
                        if(rowUpdated < r && colUpdated < c){
                            reshapedMatrix[rowUpdated][colUpdated++] = nums[i][j];
                        }
                        else if(colUpdated == c){
                            colUpdated = 0;
                            reshapedMatrix[++rowUpdated][colUpdated++] = nums[i][j];
                        }
                    }
                }
                return reshapedMatrix;
            }
            return nums;
        }

Log in to reply
 

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