leetcode rotate-image(90°旋转矩阵)
2017-05-18 09:12
633 查看
原题:
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?
题意就不多说了,比较经典的一个问题,90度顺时针旋转一个n*n的二维矩阵,难点在于只能使用O(1)的空间来存储
思路:举例说明比较清晰
对于一个3*3的矩阵 arr
1 2 3
4 5 6
7 8 9
先用一个临时变量 temp保存左上角的数字 即 temp = 1;然后按如下顺序赋值: 1 = 7, 7 = 9, 9 = 3, 3 = temp,赋值之后矩阵变为
7 2 1
4 5 6
9 8 3
之后temp = 4 按如下顺序赋值: 4 = 8, 8 = 6, 6 = 2, 2 = temp,
矩阵变为
7 4 1
8 5 2
9 6 3
这样外面一层执行了两次完成了赋值
由于内层只有一个数字5,因此结束。
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?
题意就不多说了,比较经典的一个问题,90度顺时针旋转一个n*n的二维矩阵,难点在于只能使用O(1)的空间来存储
思路:举例说明比较清晰
对于一个3*3的矩阵 arr
1 2 3
4 5 6
7 8 9
先用一个临时变量 temp保存左上角的数字 即 temp = 1;然后按如下顺序赋值: 1 = 7, 7 = 9, 9 = 3, 3 = temp,赋值之后矩阵变为
7 2 1
4 5 6
9 8 3
之后temp = 4 按如下顺序赋值: 4 = 8, 8 = 6, 6 = 2, 2 = temp,
矩阵变为
7 4 1
8 5 2
9 6 3
这样外面一层执行了两次完成了赋值
由于内层只有一个数字5,因此结束。
public class Solution { public void rotate(int[][] matrix) { int len = matrix.length; for(int i = 0;i<matrix.length/2;i++) { for(int j = i;j<matrix.length-i-1;j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[len - j -1][i]; matrix[len - j -1][i] = matrix[len - i - 1][len - j - 1]; matrix[len - i - 1][len - j - 1] = matrix[j][len - i - 1]; matrix[j][len - i - 1] = temp; } } } }
相关文章推荐
- leetcode:Rotate Image (旋转矩阵)【面试算法题】
- leetcode-48 Rotate Image 旋转矩阵
- LeetCode-48-Rotate Image 矩阵旋转90
- [leetcode]Rotate Image, Matrix tranposition, matrix rotation 90 degree @ Python
- Leetcode 48. Rotate Image
- LeetCode 48 Rotate Image(2D图像旋转问题)
- [LeetCode] 48. Rotate Image
- LeetCode - Refresh - Rotate Image
- [leetCode] Rotate Image
- 【leetcode】Rotate Image(middle)
- Leetcode5 Rotate Image
- [LeetCode] Rotate Image
- leetcode Rotate Image
- LeetCode - Rotate Image
- Leetcode_rotate-image
- Leetcode 细节实现 Rotate Image
- LeetCode-Rotate Image
- [leetcode] 48.Rotate Image
- Leetcode 实施细节 Rotate Image
- leetcode_48题——Rotate Image(矩阵计算)