LeetCode 题解工作台

转置矩阵

给你一个二维整数数组 matrix , 返回 matrix 的 转置矩阵 。 矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。 示例 1: 输入: matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出: [[1,4,7],[2,5,8],[3,6,9]] 示例…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们记矩阵 的行数为 ,列数为 。根据转置的定义,转置后的矩阵 的行数为 ,列数为 。 对于 中的任意位置 ,其对应于矩阵 中的位置 。因此,我们遍历矩阵 中的每个元素,将其转置到 中相应的位置。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二维整数数组 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.length
  • n == matrix[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 105
  • -109 <= matrix[i][j] <= 109
lightbulb

解题思路

方法一:模拟

我们记矩阵 matrix\textit{matrix} 的行数为 mm,列数为 nn。根据转置的定义,转置后的矩阵 ans\textit{ans} 的行数为 nn,列数为 mm

对于 ans\textit{ans} 中的任意位置 (i,j)(i,j),其对应于矩阵 matrix\textit{matrix} 中的位置 (j,i)(j,i)。因此,我们遍历矩阵 matrix\textit{matrix} 中的每个元素,将其转置到 ans\textit{ans} 中相应的位置。

遍历结束后,返回 ans\textit{ans} 即可。

时间复杂度 O(m×n)O(m \times n),其中 mmnn 分别是矩阵 matrix\textit{matrix} 的行数和列数。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        return list(zip(*matrix))
speed

复杂度分析

指标
时间O(R * C)
空间O(R * C)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

转置矩阵题解:数组·matrix | LeetCode #867 简单