给定一个矩阵 A, 返回 A 的转置矩阵。
矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
示例 1:
输入:[[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
输入:[[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
提示:
1 <= A.length <= 1000
1 <= A[0].length <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/transpose-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1
zip(*A)实现转置
class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
A=list(zip(*A))
return list(list(i) for i in A)
执行结果:
通过
显示详情
执行用时:72 ms, 在所有 Python 提交中击败了36.62%的用户
内存消耗:13.3 MB, 在所有 Python 提交中击败了100.00%的用户
思路2
遍历
class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
res=[]
for i in range(len(A[0])):
tmp=[]
for j in range(len(A)):
tmp.append(A[j][i])
res.append(tmp)
return res
执行结果:
通过
显示详情
执行用时:68 ms, 在所有 Python 提交中击败了52.82%的用户
内存消耗:13 MB, 在所有 Python 提交中击败了100.00%的用户