Java Beginner Solution, super easy to understand


  • 0
    E
    class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            // pre-conditions
            int r1 = nums.length;
            if (r1 == 0) return nums;
            int c1 = nums[0].length;
            if (r*c != r1*c1) return nums; // if element number not equal, cannot reform
            
            
            int[][] res = new int[r][c]; 
            int[] oneD = new int[r*c]; 
            
            int k = 0; // put into 1D array
            for (int i = 0; i < r1; i++){
                for (int j = 0; j < c1; j++){
                    oneD[k] = nums[i][j];
                    k++;
                }
            }
             
            k = 0; // get from 1D array
            for (int i = 0; i < r; i++){
                for (int j = 0; j < c; j++){
                    res[i][j] = oneD[k] ;
                    k++;
                }
            }
            
            return res;
        }
    }
    

Log in to reply
 

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