随笔- 509  文章- 0  评论- 151  阅读- 22万 

Rotate Image

2013.12.15 21:40

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?

Solution:

  Rotate an nXn 2D matrix in-place. See the picture below and that's how I did the rotation:

    ABCDA

    DEFEB

    CFXFC

    BEFED

    ADCBA

  Time complexity is O(n^2), space complexity is O(1).

Accepted code:

复制代码
 1 // 1AC, yes!!!
 2 class Solution {
 3 public:
 4     void rotate(vector<vector<int> > &matrix) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         int n;
 8         
 9         n = matrix.size();
10         
11         if(n <= 0){
12             return;
13         }
14         
15         int i, j, tmp;
16         int leni = n / 2;
17         int lenj = n - leni;
18         
19         for(i = 0; i < leni; ++i){
20             for(j = 0; j < lenj; ++j){
21                 // extra O(1)
22                 tmp = matrix[i][j];
23                 matrix[i][j] = matrix[n - 1 - j][i];
24                 matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
25                 matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
26                 matrix[j][n - 1 - i] = tmp;
27             }
28         }
29     }
30 };
复制代码

 

 posted on   zhuli19901106  阅读(279)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示