566. Reshape the Matrix

Question

566. Reshape the Matrix

Solution

题目大意:给一个二维数组,将这个二维数组转换为r行c列

思路:构造一个r行c列的二维数组,遍历给出二给数组nums,合理转换原数组和目标数组的行列转换。

Java实现:

public int[][] matrixReshape(int[][] nums, int r, int c) {
    int originalR = nums.length;
    int originalC = nums[0].length;
    if (originalR * originalC < r * c) {
        return nums;
    }
    int[][] retArr = new int[r][c];
    int count = -1;
    for (int i = 0; i < originalR; i++) {
        for (int j = 0; j < originalC; j++) {
            count++;
            int rIndex = count / c;
            int cIndex = count % c;
            // System.out.println(rIndex + "," + cIndex + "	" + i + "," + j);
            retArr[rIndex][cIndex] = nums[i][j];
            // System.out.println(nums[i][j]);
        }
    }
    return retArr;
}
原文地址:https://www.cnblogs.com/okokabcd/p/9255658.html