topic
text
Gives you a two-dimensional integer array matrix, and returns the transposed matrix of the matrix.
The transposition of a matrix refers to flipping the main diagonal of the matrix and exchanging the row index and column index of the matrix.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3 ,6,9]]
Example 2:
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
prompt:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
Source: LeetCode
template
/**
* 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().
*返回大小为* returnSize的数组。
*数组的大小作为* returnColumnSizes数组返回。
*注意:返回的数组和* columnSizes数组都必须被分配,假设调用者调用free()。
*/
int** transpose(int** matrix, int matrixSize, int* matrixColSize, int* returnSize, int** returnColumnSizes) {
}
Problem solving
analysis
This question is not difficult, just swap the elements diagonally.
Here I added the array subscripts to better discover the relationship before and after conversion.
It is obvious that the subscripts of the two-dimensional array are exchanged.
- Two-dimensional array initialization, row and column swap
int m = matrixSize, n = matrixColSize[0];
int** transposed = malloc(sizeof(int*) * n);
*returnSize = n;
*returnColumnSizes = malloc(sizeof(int) * n);
for (int i = 0; i < n; i++) {
transposed[i] = malloc(sizeof(int) * m);
(*returnColumnSizes)[i] = m;
}
- Element fill
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
transposed[j][i] = matrix[i][j];
}
}
It's that simple.
Complete source code
int** transpose(int** matrix, int matrixSize, int* matrixColSize, int* returnSize, int** returnColumnSizes) {
int m = matrixSize, n = matrixColSize[0];
int** transposed = malloc(sizeof(int*) * n);
*returnSize = n;
*returnColumnSizes = malloc(sizeof(int) * n);
for (int i = 0; i < n; i++) {
transposed[i] = malloc(sizeof(int) * m);
(*returnColumnSizes)[i] = m;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}