算法笔记 -- 566. 重塑矩阵

124 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第20天,点击查看活动详情

题目描述

原题链接 :

566. 重塑矩阵 - 力扣(LeetCode) (leetcode-cn.com)

MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。

给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 rc ,分别表示想要的重构的矩阵的行数和列数。

重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。

如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

 

示例 1:

image.png

输入:mat = [[1,2],[3,4]], r = 1, c = 4
输出:[[1,2,3,4]]

示例 2:

image.png

输入:mat = [[1,2],[3,4]], r = 2, c = 4
输出:[[1,2],[3,4]]

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

思路分析

  1. 如果resharp之后的个数与之前不一致,直接返回原来mat指针
  2. 两个for循环里,count计算当前遍历总数,新数组中的row=count/c,column=count%c(像OS中的思想)
  3. returnColumnSizes数组必须malloc申请空间,for中(*returnColumnSizes)[i]=c
  4. 一开始int retMatrix[r][c],再用两层for进行初始化,但最后会报错:
    Line 241: Char 15: runtime error: load of null pointer of type 'int *' [Serializer.c]
    解决方法是malloc两次,一次是二级指针空间,一次是一级指针空间。

AC 代码

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** matrixReshape(int** mat, int matSize, int* matColSize, int r, int c, int* returnSize, int** returnColumnSizes){
    if(r*c!=matSize*(*matColSize))
    {
        *returnSize=matSize;
        *returnColumnSizes=matColSize;
        return mat;
    }
    *returnSize=r;//返回的维度
    *returnColumnSizes=(int*)malloc(sizeof(int)*r);//申请空间
    int **retMatrix=(int**)malloc(sizeof(int*)*r);//申请二级指针空间
    for(int i;i<r;i++)
    {
        retMatrix[i]=(int*)malloc(sizeof(int)*c);//申请一级指针空间
        (*returnColumnSizes)[i]=c;
    }

    int count=0;
    for(int i=0;i<matSize;i++)
    {
        for(int j=0;j<*matColSize;j++)
        {
            count=i*(*matColSize)+j;
            retMatrix[count/c][count%c]=mat[i][j];
        }
    }
    return retMatrix;
}