Skip to content

Commit 77c7073

Browse files
committed
Runtime: 34 ms (Top 84.25%) | Memory: 16.50 MB (Top 59.83%)
1 parent 86f1276 commit 77c7073

File tree

1 file changed

+28
-41
lines changed

1 file changed

+28
-41
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,29 @@
1-
# Runtime: 61 ms (Top 26.67%) | Memory: 13.9 MB (Top 37.41%)
2-
class Solution(object):
3-
def generateMatrix(self, n):
4-
if n==1:
5-
return [[1]]
6-
matrix=[[0 for a in range(n)] for b in range(n)]
7-
le_b=0
8-
u_b=0
9-
r_b=n-1
10-
lo_b=n-1
11-
ele=1
12-
while ele<(n**2)+1:
13-
i=u_b
14-
j=le_b
15-
while ele<(n**2)+1 and j<=r_b:
16-
matrix[i][j]=ele
17-
ele+=1
18-
j+=1
19-
u_b+=1
20-
i=u_b
21-
j=r_b
22-
while ele<(n**2)+1 and i<=lo_b:
23-
matrix[i][j]=ele
24-
ele+=1
25-
i+=1
26-
r_b-=1
27-
i=lo_b
28-
j=r_b
29-
while ele<(n**2)+1 and j>=le_b:
30-
matrix[i][j]=ele
31-
ele+=1
32-
j-=1
33-
lo_b-=1
34-
i=lo_b
35-
j=le_b
36-
while ele<(n**2)+1 and i>=u_b:
37-
matrix[i][j]=ele
38-
ele+=1
39-
i-=1
40-
le_b+=1
1+
// Runtime: 34 ms (Top 84.25%) | Memory: 16.50 MB (Top 59.83%)
2+
3+
class Solution:
4+
def generateMatrix(self, n: int) -> List[List[int]]:
5+
if not n:
6+
return []
7+
matrix = [[0 for _ in range(n)] for _ in range(n)]
8+
left, right, top, bottom, num = 0, n-1, 0, n-1, 1
9+
while left <= right and top <= bottom:
10+
for i in range(left, right+1):
11+
matrix[top][i] = num
12+
num += 1
13+
top += 1
14+
for i in range(top, bottom+1):
15+
matrix[i][right] = num
16+
num += 1
17+
right -= 1
18+
if top <= bottom:
19+
for i in range(right, left-1, -1):
20+
matrix[bottom][i] = num
21+
num += 1
22+
bottom -= 1
23+
if left <= right:
24+
for i in range(bottom, top-1, -1):
25+
matrix[i][left] = num
26+
num += 1
27+
left += 1
4128
return matrix
42-
```
29+

0 commit comments

Comments
 (0)