当前位置:网站首页>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多天的刷题了
边栏推荐
- 如何防止重复下单?
- 动手学深度学习_AlexNet
- 在Markdown文件中快速插入本地图片
- codeforces:808D. Array Division【二分 + 找规律】
- seaborn
- 微信小程序获取年月日周及早上、中午、晚上
- Projector reached the party benefits 】 【 beginners entry - brightness projection and curtain selection - from entry to the master
- 现代 ABAP 编程语言中的正则表达式
- 推荐 7 月份 yyds 的开源项目
- 什么是APS?APS+MES如何解决生产难题?
猜你喜欢
随机推荐
华为应用市场“图章链接”功能上线 让APP分发突破机型壁垒
字节API鉴权方法
Visual Studio 2022创建项目没有CUDA模板的解决方法
成功 解决 @keyup.enter=“search()“ 在el-input 组件中不生效的问题
人造肉在中国还有未来吗?
DocuWare Platform - Content Services and Workflow Automation Platform for Document Management (Part 1)
【打卡】广告-信息流跨域ctr预估(待更新)
什么是APS?APS+MES如何解决生产难题?
Matlab计算随模拟时间变化的热导率
GPS卫星同步时钟,NTP网络同步时钟,北斗时钟服务器(京准)
招募 | 香港理工大学Georg Kranz 博士诚招博士
flink cdc怎么指定位点,从某个位点开始消费mysql的Binlog?
To ensure that the communication mechanism
LeetCode·每日一题·1403.非递增顺序的最小子序列·贪心
DMS 有接口获取每个实例下的数据库列表吗
SQL语言的分类以及数据库的导入
codeforces:808D. Array Division【二分 + 找规律】
跟我学 UML 系统建模
闭包及闭包的使用
5 基本引用类型