当前位置:网站首页>leetcode 48. Rotate Image 旋转图像(Medium)
leetcode 48. Rotate Image 旋转图像(Medium)
2022-08-04 16:15:00 【okokabcd】
一、题目大意
标签: 数组
https://leetcode.cn/problems/rotate-image
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]
示例 2:
输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
提示:
- n == matrix.length == matrix[i].length
- 1 <= n <= 20
- -1000 <= matrix[i][j] <= 1000
二、解题思路
一个元素每次90度旋转,旋转4次后回到原点,这样我们找出这四个点的坐标一切就简单了,令N=martrix.length-1:
(i, j)(N-j, i)(N-i, N-j)(j, N-i)
为了旋转这四个元素,我们可以用一个临时变量保存其中一个元素,然后让几个元素依次赋值。
那么,一共有多少个这样的四元素组呢?这要分情况来看。两层遍历数组,第一层i 从0到n/2,第二层j 从j到n-i,这样遍历的元素为n/4或(n-1)/4;
三、解题方法
3.1 Java实现
public class Solution {
public void rotate(int[][] matrix) {
// 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
// 输出:[[7,4,1],[8,5,2],[9,6,3]]
// x表示行 y表示列
/** * i 0->n/2 0->2 * j i->n-i i->3-i * 00 01 02 03 * 11 12 * 从上到下 (j,n-i) * 从右到左 * * (j,n-i)<-(i,j) * (i,j)<-(n-j,i) * (n-j,i)<-(n-i, n-j) */
int temp = 0;
int n = matrix.length - 1;
for (int i = 0; i <= n / 2; i++) {
for (int j = i; j < n - i; j++) {
// 0行n列
temp = matrix[j][n - i];
matrix[j][n - i] = matrix[i][j];
matrix[i][j] = matrix[n-j][i];
matrix[n-j][i] = matrix[n-i][n-j];
matrix[n-i][n-j] = temp;
}
}
}
}
四、总结小记
- 2022/8/4 需要总结一下60多天的刷题了
边栏推荐
猜你喜欢

张乐:研发效能的黄金三角及需求与敏捷协作领域的实践|直播回顾

Request method ‘POST‘ not supported。 Failed to load resource: net::ERR_FAILED

如何实时监控销售数据?销售看板来帮你!

7 月浏览器市场份额:Edge 全球第二、360 安全浏览器中国第二

面了三十个人,说说真实感受

Typora收费?搭建VS Code MarkDown写作环境

Xi'an Zongheng Information × JNPF: Adapt to the characteristics of Chinese enterprises, fully integrate the cost management and control system

What is the difference between ITSM software and a work order system?

For循环控制

不需要服务器,教你仅用30行代码搞定实时健康码识别
随机推荐
勒索软件的原理
In-depth analysis of HyperBDR cloud disaster recovery 1: Cloud-native cross-platform disaster recovery, making data flow more flexible
第三章 Scala运算符
不需要服务器,教你仅用30行代码搞定实时健康码识别
MySQL 性能调优和优化技巧
云存储硬核技术内幕——(9) 相见时难别亦难
请问一下dms的跨阿里云账户 新增实例,是不是无法新增redis ?
【Idea设置运行参数无效】可能是...
B 站又上热搜了, HR 称「核心用户都是 Loser」
云存储硬核技术内幕——(11) 女子会所的秘密
06-总线
地理标志农产品需双重保护
Summary of some pytorch knowledge points that have been updated for a long time
张乐:研发效能的黄金三角及需求与敏捷协作领域的实践
PAT 甲级 A1072 Gas Station
项目里的各种配置,你都了解吗?
【Es6中的promise】
C# 写系统日志
【Pick-in】Advertising-information flow cross-domain CTR estimation (to be updated)
饿了么智能头盔专利获授权 进一步提升骑手安全保障