Java easy to understand solution


  • 0
    S
    public class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            int size = 0;
            for(int i = 0; i<nums.length; i++){
                size = size + nums[i].length;
            }
            if(size < r*c || (size == r*c && nums.length == r)){
                return nums;
            }
           
            int[][] arr = new int[r][c];
            int k = 0;
            int m = 0;
            for(int i = 0; i<nums.length; i++){
                for(int j = 0; j<nums[i].length;j++){
                    if(k<c && m<r){
                      arr[m][k] = nums[i][j];
                        k++;  
                    }
                    if(k==c) {
                        m++;
                        k=0;
                    }
                    
                }
               
            }
            return arr;
        }
    }
    

Log in to reply
 

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