1. 程式人生 > >566. Reshape the Matrix - LeetCode

566. Reshape the Matrix - LeetCode

pub clas tar ava 圖片 des tps 遍歷 gin

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 + "\t" + i + "," + j);
            retArr[rIndex][cIndex] = nums[i][j];
            // System.out.println(nums[i][j]);
        }
    }
    return retArr;
}

566. Reshape the Matrix - LeetCode