Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bc9dcb8

Browse files
committed
Update array.md
旋转矩阵
1 parent 7499e15 commit bc9dcb8

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

‎data_structure/array.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,65 @@ vector<int> spiralOrder(vector<vector<int>>& matrix) {
363363
}
364364
```
365365
366+
**Python版本一**
367+
```python
368+
class Solution:
369+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
370+
rows = len(matrix)
371+
cols = len(matrix[0])
372+
rl, rh = 0, rows - 1
373+
cl, ch = 0, cols - 1
374+
375+
res = list()
376+
while True:
377+
i = cl
378+
while i <= ch:
379+
res.append(matrix[rl][i])
380+
i = i + 1
381+
rl = rl + 1
382+
if rl > rh: break
383+
384+
i = rl
385+
while i <= rh:
386+
res.append(matrix[i][ch])
387+
i = i + 1
388+
ch = ch - 1
389+
if ch < cl: break
390+
391+
i = ch
392+
while i >= cl:
393+
res.append(matrix[rh][i])
394+
i = i - 1
395+
rh = rh - 1
396+
if rh < rl: break
397+
398+
i = rh
399+
while i >= rl:
400+
res.append(matrix[i][cl])
401+
i = i - 1
402+
cl = cl + 1
403+
if cl > ch: break
404+
405+
return res
406+
```
407+
408+
新思路:我们可以每次旋转90度matrix,然后直接取第一行的数即可。
409+
410+
**Python版本二**
411+
```python
412+
class Solution:
413+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
414+
res = list()
415+
while matrix:
416+
res.extend(matrix.pop(0))
417+
# 矩阵旋转90度
418+
matrix = list(zip(*matrix))[::-1]
419+
420+
return res
421+
```
422+
423+
424+
366425
## 练习题
367426
- [ ] [移除元素](https://leetcode.cn/problems/remove-element/)
368427
- [ ] [删除有序数组中的重复项](https://leetcode.cn/problems/remove-duplicates-from-sorted-array/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /