天天看点

【leetcode】#566 Reshape the Matrix 重塑矩阵 改变矩阵维度 理解matColSize

目录

    • 题目
    • 函数
    • 分析
    • 程序实现
    • 总结
    • 资料

题目

英文题目

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the row number and column number of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

中文题目

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

给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。

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

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

示例1

输入:

nums =

[[1,2],

[3,4]]

r = 1, c = 4

输出:

[[1,2,3,4]]

解释:

行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。

示例2

输入:

nums =

[[1,2],

[3,4]]

r = 2, c = 4

输出:

[[1,2],

[3,4]]

解释:

没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。

说明

给定矩阵的宽和高范围在 [1, 100]。

给定的 r 和 c 都是正数

函数

/**
 * 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){

}
           

分析

程序很容易实现,但 leetcode 给的实现函数里的返回值,传入值,有些不清楚,这里借用一下题解中的图片

【leetcode】#566 Reshape the Matrix 重塑矩阵 改变矩阵维度 理解matColSize

note: 图片中的 Nums 替换为 mat

程序实现

/**
 * 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){
	int m = matSize; // 矩阵的行数
	int n = matColSize[0]; // 数组matColSize 存储 矩阵每一行的列数
	// 不能重塑
	if (m * n != r * c){
		*returnSize = m; // 返回的矩阵有多少行
		*returnColumnSizes = matColSize; // 返回一个数组,即每一行的列数
		return mat;
	}
	// 可以重塑
	*returnSize = r;
	*returnColumnSizes = malloc(sizeof(int) * r); // 为返回的数组分配空间
	int** array = malloc(sizeof(int*) * r); // 指向 r 行数组,还未给每一行分配空间
	for (int i = 0; i < r; i++){
		// 这种赋值还需再学习
		// *(*returnColumnSizes + i) = c;
		(*returnColumnSizes)[i] = c; // 每一行有 c 列
		array[i] = malloc(sizeof(int) * c); // 每一行的空间
	}
	for (int j = 0; j < m * n; j++){
		array[j / c][j % c] = mat[j / n][j % n];
	}
	return array;
	
}
           

总结

  • m m m行 n n n的矩阵reshape成一维数组 [ 0 , m n ] [0,mn] [0,mn]时

    ( i , j ) → i ∗ n + j (i,j) \rightarrow i*n+j (i,j)→i∗n+j

    映射回去时:

    i = x / n i = x/n i=x/n

    j = x % n j = x\%n j=x%n

  • 内存管理!!!

资料

题目

题解