Transpose Matrix leetCode Problem
Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
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]]
Code 1:
class Solution {
public int[][] transpose(int[][] matrix) {
int rows = matrix.length; // Number of rows
int cols = matrix[0].length; // Number of columns
int[][] transposed = new int[cols][rows]; // Create a new matrix with swapped dimensions
// Fill the transposed matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j]; // Swap rows and columns
}
}
return transposed; // Return the new transposed matrix
}
}
Code 2:
public class codefile{
static List<List<Integer>> solve(List<List<Integer>> input){
int row=input.size();
int col=input.get(0).size();
List<List<Integer>> transpose = new ArrayList<>();
for(int i=0;i<col;i++)
{
transpose.add(new ArrayList<>());
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
transpose.get(j).add(input.get(i).get(j));
}
}
return transpose;
}
}
Comments
Post a Comment