-
Notifications
You must be signed in to change notification settings - Fork 43
/
transpose-matrix.py
57 lines (53 loc) · 1.41 KB
/
transpose-matrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# V0
# V1
# https://www.jiuzhang.com/solution/transpose-matrix/#tag-highlight-lang-python
class Solution:
"""
@param A: A matrix
@return: A transposed matrix
"""
def transpose(self, A):
# write your code here
n, m = len(A), len(A[0])
ans=[[0 for i in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
ans[i][j]=A[j][i]
return ans
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/81015450
class Solution:
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
rows, cols = len(A), len(A[0])
res = [[0] * rows for _ in range(cols)]
for row in range(rows):
for col in range(cols):
res[col][row] = A[row][col]
return res
# V2
# Time: O(r * c)
# Space: O(1)
class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
result = [[None] * len(A) for _ in range(len(A[0]))]
for r, row in enumerate(A):
for c, val in enumerate(row):
result[c][r] = val
return result
# Time: O(r * c)
# Space: O(1)
class Solution2(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
return zip(*A)