The title
portal
The text
Given a two-dimensional integer array matrix, return the transpose of matrix.
The transpose of a matrix is to reverse the main diagonal of the matrix and swap the row index and column index of the matrix.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]
,4,7 output: [[1], [2,5,8], [3,6,9]]
Example 2:
Matrix = [[1,2,3],[4,5,6]]
Output: [[1, 4], [2, 5], [3]]
Tip:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
Copy the code
Source: LeetCode
The 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(). * Returns an array with a size of * returnSize. The size of the * array is returned as * returnColumnSizes array. * Note: Both the returned array and * columnSizes array must be allocated, assuming the caller calls free (). * /
int** transpose(int** matrix, int matrixSize, int* matrixColSize, int* returnSize, int** returnColumnSizes) {}Copy the code
The problem solving
Analysis of the
It’s not that hard to just switch diagonallyI’ve added an array index here, just to make it easier to see what’s going on before and after. It’s pretty obvious that you’re swapping the indices of a two-dimensional array.
- Initializes a two-dimensional array, with rows and columns switched
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;
}
Copy the code
- Element filling
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) { transposed[j][i] = matrix[i][j]; }}Copy the code
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;
}
Copy the code