Java simple try-catch solution


  • 0
    E
    class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            int[][] res = new int[r][c];
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < nums.length; i++)
                for (int j = 0; j < nums[0].length; j++)
                    list.add(nums[i][j]);
            try {
                for (int i = 0; i < r; i++) {
                    for (int j = 0; j < c; j++)
                        res[i][j] = list.get(i*c + j);
                }
                return res;
            }
            catch (Exception e) { return nums;}
        }
    }
    

Log in to reply
 

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