[C++] [Java] Clean Code - 5 lines (2 Solution)


  • 6

    Java

    class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            int m = nums.length, n = nums[0].length, o = m * n;
            if (r * c != o) return nums;
            int[][] res = new int[r][c];
            for (int i = 0; i < o; i++) res[i / c][i % c] = nums[i / n][i % n];
            return res;        
        }
    }
    

    C++

    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int m = nums.size(), n = nums[0].size(), o = m * n;
            if (r * c != o) return nums;
            vector<vector<int>> res(r, vector<int>(c, 0));
            for (int i = 0; i < o; i++) res[i / c][i % c] = nums[i / n][i % n];
            return res;
        }
    };
    
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
            int m = nums.size(), n = nums[0].size();
            if (m * n != r * c) {
                return nums;
            }
    
            vector<vector<int>> res(r, vector<int>(c, 0));
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    int k = i * n + j;
                    res[k / c][k % c] = nums[i][j];
                }
            }
    
            return res;
        }
    };
    

  • 0
    S
    This post is deleted!

  • 2
    V

    There is no need to re-calculate k every time, just do it like this:

    for (int i = 0, k = 0; i < m; i++)
        for (int j = 0; j < n; j++, k++)
            res[k / c][k % c] = nums[i][j];
    

  • 0
    J
    public class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            if (nums == null || nums.length == 0 || nums[0].length == 0) return nums;
            if (nums.length * nums[0].length != r * c) return nums;
            
            int reshapeCnt = 0;
            int[][] reshapedNums = new int[r][c];
            for (int row = 0; row < nums.length; row++) {
                for (int col = 0; col < nums[0].length; col++) {
                    reshapedNums[reshapeCnt / c][reshapeCnt % c] = nums[row][col];
                    reshapeCnt++;
                }
            }
            
            return reshapedNums;
        }
    }
    
    

  • 0
    R

    @vicch7 Lucid solution, thanks. :)


Log in to reply
 

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