leetcode.array--48. Rotate Image
来源:互联网 发布:10.1.1越狱抹掉数据 编辑:程序博客网 时间:2024/06/06 21:46
题目:48. Rotate Image
题目描述:https://leetcode.com/problems/rotate-image/description/
意思是说,给定一个NxN的矩阵,将该矩阵顺时针旋转90度。要求不能分配新的二维矩阵,只能在原有的矩阵上进行修改。
我是这么写的:用zip()和map()实现矩阵转置,然后再把矩阵的每一行反转。由于zip()和map()均返回一个生成器,于是并没有再分配另一个矩阵空间。
Python:
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ def reverse(nums): length=len(nums) for i in range(length//2): nums[i],nums[length-i-1]=nums[length-i-1],nums[i] return tempGene=map(list,zip(*matrix)) del matrix[:] for item in tempGene: matrix.append(item) for i in range(len(matrix)): reverse(matrix[i]) # print(matrix) return
结束了吗?没有。实际上Python3中的zip()和map()才会返回一个生成器,而Python2中这两个函数的返回值是List(列表),也就是说,上面代码中的tempGene在Python2中是一个列表,不符合题意。于是改成下面这样:
Python:
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ def reverse(nums): length=len(nums) for i in range(length//2): nums[i],nums[length-i-1]=nums[length-i-1],nums[i] return for i in range(len(matrix)): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for item in matrix: reverse(item) return
结束了吗?还没。上面的矩阵变换等价于:先交换矩阵的行,再进行转置,于是又可以写成这样:
Python:
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ rows=len(matrix) for i in range(rows//2): matrix[i],matrix[rows-i-1]=matrix[rows-i-1],matrix[i] for i in range(len(matrix)): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] return
阅读全文
0 0
- leetcode.array--48. Rotate Image
- LeetCode[Array]: Rotate Image
- [leetcode][Array] Rotate Image
- [LeetCode]48.Rotate Image
- LeetCode 48. Rotate Image
- LeetCode 48.Rotate Image
- LeetCode --- 48. Rotate Image
- [Leetcode] 48. Rotate Image
- [leetcode] 48. Rotate Image
- Leetcode 48. Rotate Image
- 48. Rotate Image LeetCode
- [LeetCode]48. Rotate Image
- leetcode 48. Rotate Image
- Leetcode 48. Rotate Image
- LeetCode 48. Rotate Image
- LeetCode *** 48. Rotate Image
- [LeetCode]48. Rotate Image
- LeetCode 48. Rotate Image
- 5.MariaDB笔记——MariaDB开发者
- linux c程序中内核态与用户态内存存储问题
- CentOS7搭建FTP服务器
- 实验吧 这个FLAG有点怪 By Assassin
- spark安装教程
- leetcode.array--48. Rotate Image
- Android自定义控件(一) 自定义组合控件
- 6.MariaDB笔记——cmake使用介绍一
- hdu 1569 最小割
- 排查Linux机器是否已经被入侵
- 1701H5 范江睿 10月11日 连续第一天总结
- Java8 I/O源码-ByteArrayOutputStream
- 字符串算法——最长回文子串
- 工作周记