当前位置:网站首页>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多天的刷题了
边栏推荐
- 微信小程序获取年月日周及早上、中午、晚上
- 开源一夏 | 请你谈谈网站是如何进行访问的?【web领域面试题】
- 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?
- 【Idea设置运行参数无效】可能是...
- 什么是会话劫持攻击以及如何防止会话劫持
- 转型阵痛期,好未来减亏容易增收难?
- UWP 转换 IBuffer 和其他类型
- Projector reached the party benefits 】 【 beginners entry - brightness projection and curtain selection - from entry to the master
- 在Markdown文件中快速插入本地图片
猜你喜欢
911S5正式谢幕后 如何找到一个好用的替代品
【IDEA】idea配置
What is an artifact library in a DevOps platform?What's the use?
现代 ABAP 编程语言中的正则表达式
It took half a month to finally make a collection of high-frequency interview questions of first-tier manufacturers
项目里的各种配置,你都了解吗?
In action: 10 ways to implement delayed tasks, with code!
吴恩达机器学习[12]-机器学习系统设计
8年软件测试感悟,送给刚入测试行业的小伙伴
Visual Studio 2022创建项目没有CUDA模板的解决方法
随机推荐
农产品期货开户哪家好??
5 基本引用类型
第三章 Scala运算符
软件性能测试包括哪些内容?国内权威软件检测机构排名
HCIP笔记(7)
Request method ‘POST‘ not supported。 Failed to load resource: net::ERR_FAILED
录音文件识别
历史上的今天:微软研究院的创始人诞生;陌陌正式上线;苹果发布 Newton OS
不需要服务器,教你仅用30行代码搞定实时健康码识别
HCIP笔记(6)
flink cdc怎么指定位点,从某个位点开始消费mysql的Binlog?
微信小程序获取年月日周及早上、中午、晚上
Pulsar消费者处理不当导致的消息积压问题
inter-process communication
无心剑七绝《七夕牵手》
面试官:多个线程执行完毕后,才执行另一个线程,该怎么做?
花了半个月,终于把一线大厂高频面试题做成合集了
Steady Development | Data and Insights on Mobile Game Players in Western Europe
UWP WPF 解决 xaml 设计显示异常
Check which user permissions are assigned to each database, is there an interface for this?