天天看點

【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

  • 記憶體管理!!!

資料

題目

題解