【Leetcode】566. Reshape the Matrix

题目地址:

https://leetcode.com/problems/reshape-the-matrix/

给定一个矩阵,要求将其变换为一个rrcc列的矩阵,使得两者按行遍历结果一样。若无法变换,则返回原矩阵。用一维转二维的方法,将一个一维座标和二维座标做一一对应即可。代码如下:

public class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int n = nums.length, m = nums[0].length;
        // 如果方格个数不一样则不可能转换成功,返回原数组即可
        if (n * m != r * c) {
            return nums;
        }
        
        int[][] res = new int[r][c];
        int idx = 0;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
            	// idx对应的二维座标是(idx / c, idx % c)
                res[idx / c][idx % c] = nums[i][j];
                idx++;
            }
        }
        
        return res;
    }
}

时间复杂度O(nm)O(nm),空间O(1)O(1)(不包含返回结果的空间)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章