LeetCode 566. 重塑矩阵

题目描述

566. 重塑矩阵

思路分析

解法一:数学映射(推荐)

核心思路

  • 首先检查合法性:原矩阵元素总数 m * n 必须等于目标 r * c,否则直接返回原矩阵。
  • 将二维坐标映射为线性索引:元素在原矩阵中的线性序号 idx = i * n + j
  • 由线性序号推导目标坐标:目标行 idx / c,目标列 idx % c
  • 一次遍历即可完成重塑,无需额外辅助数据结构。


复杂度分析

  • 时间复杂度:O(m × n),其中 m、n 为原矩阵行列数
  • 空间复杂度:O(1),输出矩阵不计入额外空间
class Solution {
  public int[][] matrixReshape(int[][] mat, int r, int c) {
    int m = mat.length;
    int n = mat[0].length;

    // 元素总数不匹配,返回原矩阵
    if (m * n != r * c) {
      return mat;
    }

    int[][] result = new int[r][c];

    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        // 线性序号映射到目标坐标
        int idx = i * n + j;
        result[idx / c][idx % c] = mat[i][j];
      }
    }

    return result;
  }
}
func matrixReshape(mat [][]int, r int, c int) [][]int {
    m, n := len(mat), len(mat[0])

    // 元素总数不匹配,返回原矩阵
    if m*n != r*c {
        return mat
    }

    result := make([][]int, r)
    for i := range result {
        result[i] = make([]int, c)
    }

    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            // 线性序号映射到目标坐标
            idx := i*n + j
            result[idx/c][idx%c] = mat[i][j]
        }
    }

    return result
}

相似题目

题目 难度 考察点
48. 旋转图像 中等 矩阵、数学
54. 螺旋矩阵 中等 矩阵、模拟
59. 螺旋矩阵 II 中等 矩阵、模拟
74. 搜索二维矩阵 中等 矩阵、二分
867. 转置矩阵 简单 矩阵、模拟
1351. 统计有序矩阵中的负数 简单 矩阵、二分
本文作者:
本文链接: https://hgnulb.github.io/blog/2021/42773778
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!