重塑矩陣

題目概述

給出一個由二維數組表示的矩陣,以及兩個正整數 r 和 c,分別表示想要的重構的矩陣的行數和列數java

重構後的矩陣須要將原始矩陣的全部元素以相同的行遍歷順序填充數組

若是具備給定參數的 reshape 操做是可行且合理的,則輸出新的重塑矩陣;不然,輸出原始矩陣code

示例一以下:io

輸入: 
nums = [[1,2],[3,4]]
r = 1, c = 4
輸出: 
[[1,2,3,4]]
解釋:
行遍歷 nums 的結果是 [1,2,3,4],新的矩陣是 1 * 4 矩陣,用以前的元素值一行一行填充新矩陣

示例二以下:class

輸入: 
nums = [[1,2],[3,4]]
r = 2, c = 4
輸出: 
[[1,2],[3,4]]
解釋:
沒有辦法將 2 * 2 矩陣轉化爲 2 * 4 矩陣。 因此輸出原矩陣

解題思路

最簡單的思路,遍歷原數組,將元素放進新數組裏邊,設置兩個標誌位防止下標越界重構

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int row = nums.length;
        int col = nums[0].length;
        int eleCount = row * col;
        if(eleCount != r * c) {
            return nums;
        }
        int colFlag = 0;
        int rowFlag = 0;
        int[][] newNums = new int[r][c];
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(colFlag == c) {
                    rowFlag++;
                    colFlag = 0;
                }
                newNums[rowFlag][colFlag] = nums[i][j];
                colFlag++;
            }
        }
        return newNums;
    }
}

另外一種思路是按照下面的規則直接將元素映射到新數組中遍歷

  • 設 nums 爲 m 行 n 列,x = m * n,咱們能夠將整數 x 映射回其在矩陣中的下標,即
    • i = x / n
    • j = x % n
class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }
        int[][] ans = new int[r][c];
        for (int x = 0; x < m * n; ++x) {
            ans[x / c][x % c] = nums[x / n][x % n];
        }
        return ans;
    }
}
相關文章
相關標籤/搜索