48. Rotate Image
来源:互联网 发布:超声波灭鼠软件 编辑:程序博客网 时间:2024/06/05 18:03
题意:将N×N的矩阵顺时针旋转90度。
思路:这题直接从旋转之后索引的变换开始考虑,自顶向下,从左到右,其实就是将对应四边的四个点顺时针旋转向右移一位,就是(x,y),(y,n-x),(n-x,n-y),(n-y,x) = (n-y,x),(x,y)(y,n-x),(n-x,n-y) ,再确定下循环次数就可以了。
方法一:
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix)-1 for i in xrange(len(matrix)/2): x, y = i, i for j in xrange(n - i * 2): matrix[x][y], matrix[y][n - x], matrix[n - x][n - y], matrix[n - y][x] = matrix[n - y][x], matrix[x][y], matrix[y][n - x], matrix[n - x][n - y] y += 1
这里其实这里索引这块还是有点麻烦的,后来看到有人做的方法比我这个看要简洁一点,方法二:
class Solution: def rotate(self, A): n = len(A) for i in range(n/2): for j in range(n-n/2): A[i][j], A[~j][i], A[~i][~j], A[j][~i] = \ A[~j][i], A[~i][~j], A[j][~i], A[i][j]
这里的这个~真的是厉害,好好思考,0,1,2对应~为-1,-2,-3, n-i不就是~i吗,而且注意它这里两个for的设置和我又有些不同,它是将矩阵分为四块来旋转的。
当然了,既然是矩阵,肯定有数学方法来解,方法三:
class Solution: def rotate(self, A): A.reverse() for i in range(len(A)): for j in range(i): A[i][j], A[j][i] = A[j][i], A[i][j]
这里先行转置,再对角转置,当然也可以先逆对角转置,再行转置都是可以的。当然,最后还有一个pythonic的方法,但是并不算是in-place的方法,方法四:
class Solution2: # @param matrix, a list of lists of integers # @return a list of lists of integers def rotate(self, matrix): return [list(reversed(x)) for x in zip(*matrix)]
这里利用了解包的方法,zip(*)相当于按矩阵各列优先来重排了矩阵,但是返回的是元组,之后再reversed即可。最后附一个大神写的七种方法链接 戳我。
0 0
- [LeetCode]48.Rotate Image
- LeetCode 48. Rotate Image
- LeetCode 48.Rotate Image
- LeetCode --- 48. Rotate Image
- [Leetcode] 48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- [leetcode] 48. Rotate Image
- Leetcode 48. Rotate Image
- 48. Rotate Image LeetCode
- [LeetCode]48. Rotate Image
- 48. Rotate Image
- 48. Rotate Image
- leetcode 48. Rotate Image
- Leetcode 48. Rotate Image
- LeetCode 48. Rotate Image
- 怎样通过Jquery获取ViewBag.Title
- Webpack无法编译ES6文件的原因分析
- 在广播接收器里启动活动的注意事项
- Webpack错误解决(二): Cannot resolve 'file' or 'directory'
- 路由配置与管理——RIP路由配置与管理2
- 48. Rotate Image
- 欢迎使用CSDN-markdown编辑器
- html5 canvas元素渐变
- iOS 友盟分享实现过程
- Logistic 回归详解 交叉验证概念
- 修改nginx文件上传大小限制(413 Request Entity Too Large错误解决)
- 彻底理解原型、原型链、new操作符、prototype、__proto__、constructor等属性的概念
- onCreate(Bundle savedInstanceState, PersistableBundle persistentState),被它欺负了
- SaltStack学习笔记