54. Spiral Matrix
来源:互联网 发布:windows更新是什么 编辑:程序博客网 时间:2024/05/08 19:58
题意:给定一个m行,n列的矩阵,按螺旋顺序返回所有元素的值。
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
思路:碰到这类矩阵的题,还是要从索引的范围和规律入手,我一开始是想把矩阵转化为ndarry,就可以直接取一行的值了,之后按48题的思路做,但是后来仔细一看,原来这题不是方阵,哎,接看代码吧。
方法一:
def spiralOrder(self, matrix): if not matrix or not matrix[0]: return [] ans = [] m, n = len(matrix), len(matrix[0]) u, d, l, r = 0, m - 1, 0, n - 1 while l < r and u < d: ans.extend([matrix[u][j] for j in xrange(l, r)]) ans.extend([matrix[i][r] for i in xrange(u, d)]) ans.extend([matrix[d][j] for j in xrange(r, l, -1)]) ans.extend([matrix[i][l] for i in xrange(d, u, -1)]) u, d, l, r = u + 1, d - 1, l + 1, r - 1 if l == r: ans.extend([matrix[i][r] for i in xrange(u, d + 1)]) elif u == d: ans.extend([matrix[u][j] for j in xrange(l, r + 1)]) return ans
方法二:
def spiralOrder(self, matrix): return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])
这方法简直了,但是貌似不能用于太大的矩阵,因为解包并不是很方便,但是这个递归的思路确实挺别致的。
0 0
- 54. Spiral Matrix && 59. Spiral Matrix II
- 59. Spiral Matrix II && 54. Spiral Matrix
- LeetCode 54. Spiral Matrix
- [LeetCode]54.Spiral Matrix
- LeetCode --- 54. Spiral Matrix
- [Leetcode] 54. Spiral Matrix
- [leetcode] 54.Spiral Matrix
- 54. Spiral Matrix
- Leetcode-54.Spiral Matrix
- **LeetCode 54. Spiral Matrix
- Leetcode 54. Spiral Matrix
- [leetcode] 54. Spiral Matrix
- 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- 54. Spiral Matrix LeetCode
- 54. Spiral Matrix
- 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- linux下使用PHPExcel
- org/apache/cxf/interceptor/InterceptorProvider : Unsupported major.minor version 51.0
- android中设置AlertDialog的大小 .
- 投影矩阵与最小二乘
- 修改完wamp密码后出现服务器拒绝访问
- 54. Spiral Matrix
- 设计模式:单例模式
- Design Support Library(材料设计兼容库)
- 淘宝网的购物返现券怎么用,淘宝优惠券免费领取 淘宝购物分享红包
- Spring的配置文件ApplicationContext.xml配置头文件解析
- 在Linux下将PNG和JPG批量互转的四种方法
- jQuery
- 深度学习-最优化笔记
- 内部排序算法之五【二分插入算法】