LeetCode 题解工作台
转置矩阵
给你一个二维整数数组 matrix , 返回 matrix 的 转置矩阵 。 矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 示例 1: 输入: matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出: [[1,4,7],[2,5,8],[3,6,9]] 示例…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·matrix
答案摘要
我们记矩阵 的行数为 ,列数为 。根据转置的定义,转置后的矩阵 的行数为 ,列数为 。 对于 中的任意位置 ,其对应于矩阵 中的位置 。因此,我们遍历矩阵 中的每个元素,将其转置到 中相应的位置。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。
矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
输入:matrix = [[1,2,3],[4,5,6]] 输出:[[1,4],[2,5],[3,6]]
提示:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10001 <= m * n <= 105-109 <= matrix[i][j] <= 109
解题思路
方法一:模拟
我们记矩阵 的行数为 ,列数为 。根据转置的定义,转置后的矩阵 的行数为 ,列数为 。
对于 中的任意位置 ,其对应于矩阵 中的位置 。因此,我们遍历矩阵 中的每个元素,将其转置到 中相应的位置。
遍历结束后,返回 即可。
时间复杂度 ,其中 和 分别是矩阵 的行数和列数。忽略答案的空间消耗,空间复杂度 。
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return list(zip(*matrix))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(R * C) |
| 空间 | O(R * C) |
面试官常问的追问
外企场景- question_mark
Candidate handles basic matrix manipulation problems well.
- question_mark
Candidate uses space efficiently when applicable.
- question_mark
Candidate shows understanding of matrix properties and problem constraints.
常见陷阱
外企场景- error
Incorrectly swapping rows and columns, leading to a mismatched result.
- error
Overcomplicating the problem by trying to use advanced algorithms.
- error
Failing to account for non-square matrices and assuming the transpose is always symmetric.
进阶变体
外企场景- arrow_right_alt
Transposing a matrix in-place without extra space.
- arrow_right_alt
Transposing a matrix where rows and columns have different lengths.
- arrow_right_alt
Handling extremely large matrices with efficient time and space complexity.