Skip to content

Commit ffa9581

Browse files
committedDec 26, 2020
feat: spiral-matrix
1 parent af6df47 commit ffa9581

File tree

2 files changed

+64
-2
lines changed

2 files changed

+64
-2
lines changed
 

Diff for: ‎arr.spiral-matrix.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
54. 螺旋矩阵
6+
https://leetcode-cn.com/problems/spiral-matrix/
7+
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
8+
"""
9+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
10+
result = []
11+
if len(matrix) == 0:
12+
return result
13+
14+
left, right, up, down = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
15+
16+
x, y = 0, 0
17+
while left <= right and up <= down:
18+
# 向右移动
19+
y = left
20+
while y <= right and self.avoid(left, right, up, down):
21+
result.append(matrix[x][y])
22+
y += 1
23+
y -= 1
24+
up += 1
25+
26+
# 向下移动
27+
x = up
28+
while x <= down and self.avoid(left, right, up, down):
29+
result.append(matrix[x][y])
30+
x += 1
31+
x -= 1
32+
right -= 1
33+
34+
# 向左移动
35+
y = right
36+
while y >= left and self.avoid(left, right, up, down):
37+
result.append(matrix[x][y])
38+
y -= 1
39+
y += 1
40+
down -= 1
41+
42+
# 向上移动
43+
x = down
44+
while x >= up and self.avoid(left, right, up, down):
45+
result.append(matrix[x][y])
46+
x -= 1
47+
x += 1
48+
left += 1
49+
return result
50+
51+
def avoid(self, left, right, up, down):
52+
return left <= right and up <= down
53+
54+
55+
so = Solution()
56+
# [1,2,3,6,9,8,7,4,5]
57+
print(so.spiralOrder([
58+
[ 1, 2, 3 ],
59+
[ 4, 5, 6 ],
60+
[ 7, 8, 9 ]
61+
]))
62+

Diff for: ‎bs.find-minimum-in-rotated-sorted-array-ii.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ def findMin(self, nums: List[int]) -> int:
1515
while l < r:
1616
mid = l + (r - l) // 2
1717
# 左侧是单调的,旋转发生在右侧
18-
if nums[r] < nums[mid]:
18+
if nums[mid] > nums[r]:
1919
l = mid + 1
20-
elif nums[r] > nums[mid]:
20+
elif nums[mid] < nums[r]:
2121
r = mid
2222
else:
2323
r -= 1

0 commit comments

Comments
 (0)
Please sign in to comment.