leetcode 【 Rotate Image 】python 实现
2015-01-18 23:10
141 查看
题目:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
代码:oj测试通过 Runtime: 53 ms
思路:
题意是将一个矩阵顺时针旋转90°
小白的解决方法是由外层向里层逐层旋转;每层能够组成正方形对角线的四个元素依次窜一个位置(a b c d 变成 d a b c)。
四个元素转换位置的时候用到一个数组操作的技巧,每次都要第一个位置的元素当成tmp,交换第一个位置的元素与指针所指元素的位置。
原始:a b c d
第一次交换:b a c d
第二次交换:c a b d
第三次交换:d a b c
这样的好处是代码简洁一些 思路比较连贯
Tips:
每层循环的边界条件一定要考虑清楚,小白一开始最外层循环的上届一直写成了N,导致一直不通过,实在是太低级的错误。以后还要加强代码的熟练度,避免出现这样的低级判断错误。
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
代码:oj测试通过 Runtime: 53 ms
class Solution: # @param matrix, a list of lists of integers # @return a list of lists of integers def rotate(self, matrix): if matrix is None: return None if len(matrix[0]) < 2 : return matrix N = len(matrix[0]) for i in range(0, N/2, 1): for j in range(i, N-i-1, 1): ori_row = i ori_col = j row = ori_row col = ori_col for times in range(3): new_row = col new_col = N-row-1 matrix[ori_row][ori_col],matrix[new_row][new_col] = matrix[new_row][new_col],matrix[ori_row][ori_col] row = new_row col = new_col return matrix
思路:
题意是将一个矩阵顺时针旋转90°
小白的解决方法是由外层向里层逐层旋转;每层能够组成正方形对角线的四个元素依次窜一个位置(a b c d 变成 d a b c)。
四个元素转换位置的时候用到一个数组操作的技巧,每次都要第一个位置的元素当成tmp,交换第一个位置的元素与指针所指元素的位置。
原始:a b c d
第一次交换:b a c d
第二次交换:c a b d
第三次交换:d a b c
这样的好处是代码简洁一些 思路比较连贯
Tips:
每层循环的边界条件一定要考虑清楚,小白一开始最外层循环的上届一直写成了N,导致一直不通过,实在是太低级的错误。以后还要加强代码的熟练度,避免出现这样的低级判断错误。
相关文章推荐
- [leetcode]Rotate Image, Matrix tranposition, matrix rotation 90 degree @ Python
- 【LeetCode with Python】 Rotate Image
- 【LeetCode】【Python题解】Rotate Image
- LeetCode 61. Rotate List---Python实现
- 【LeetCode】48. Rotate Image 解题报告(Python)
- 48. Rotate Image Leetcode Python
- LeetCode--Rotate Image(旋转图像)Python
- 【LEETCODE】48-Rotate Image [Python]
- Leetcode 细节实现 Rotate Image
- LeetCode 之 Rotate Image — C/C++ 实现
- LeetCode 61. Rotate List(Python详解及实现)
- 【Leetcode】【python】Rotate Image
- [LeetCode]Rotate Image@python@python
- leetcode Rotate list (链表旋转)的python实现
- [LeetCode]题解(python):048-Rotate Image
- leetcode 【Rotate List 】python 实现
- Leetcode 细节实现 Rotate Image
- LeetCode-48-Rotate Image(C语言实现)
- [leetcode]Rotate Image @ Python
- LeetCode Rotate Image