【Leetcode】48. Rotate Image
来源:互联网 发布:苏州教师网络培训 编辑:程序博客网 时间:2024/05/21 07:08
题目分析:
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?
Subscribe to see which companies asked this question
题目的大意是:
给你一个n*n的2D矩阵,你需要旋转这个矩阵90度~
example:[[1,2,3],[4,5,6],[7,8,9]] to [[7,4,1],[8,5,2],[9,6,3]] 大家可以写纸上~这样就很明白了~
大家推演推演就可以知道,matrix[i][j] = matrix[new_i][new_j]转换的关系是:new_i ->n+1-j || new_j->i
另外一个要注意的问题就是:要注意如何遍历矩阵,要知道如果你将matrix[i][j]用目标元素替换了,你就不能再获得matrix[i][j]的原始数据了。
思路一:备份一个输入矩阵,然后按照转换关系遍历矩阵就行了。时间复杂度O(n*2) 空间复杂度O(n*2)
思路二:如果我们接着分析,我们可以发现显然没有必要备份一个矩阵。
我们可以发现这个替换关系是:a<-b,b<-c,c-<d,d<-a。(大家可以举一个二维的例子试试)
所以每次我们只需要备份a,然后完成这样一个循环就行了。
接着分析,实际上矩阵的外围只可能映射到外围上。所以每次我们只需要映射完矩阵的外围,然后找矩阵的内嵌矩阵接着进行这样的操作就可以了。这样的过程类似“回”这样一个结构。
所以最后:时间复杂度O(n*2) 空间复杂度O(1)
贴上代码:
public class Solution {
public void rotate(int[][] matrix) {
int temp;
int a,b,new_a,new_b;
for(int i=0;i<matrix.length-i;i++){
for(int j=i;j<matrix.length-i-1;j++){
a =i;b=j;
temp = matrix[a][b];
new_b= a;
new_a = matrix.length-1-b;
matrix[a][b] = matrix[new_a][new_b];
b = new_a;
a = matrix.length-1-new_b;
matrix[new_a][new_b] = matrix[a][b];
new_b = a;
new_a = matrix.length-1-b;
matrix[a][b] = matrix[new_a][new_b];
matrix[new_a][new_b] = temp;
}
}
}
}
运行结果:
运行的速度估计跟服务器当前的负载情况有关,仅供参考~
- [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
- LeetCode-48.Rotate Image
- [LeetCode] 48. Rotate Image
- LeetCode 48. Rotate Image
- freeswitch修改mod_sofia
- iOS各种调试技巧豪华套餐
- Redis2.8从入门到精通文档
- QQ登录遇到的坑
- 符号三角形问题(dfs)
- 【Leetcode】48. Rotate Image
- 学习中的知识点:
- python 生成uuid
- 优秀文章的链接收藏
- jQuery初始化select选项
- ubuntu 进入 recovery mode 修改系统文件
- 获取当前打开剪贴板的进程的ID
- express的简单安装
- Oracle闪回技术详解