LeetCode

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 };
原文地址:https://www.cnblogs.com/zhuli19901106/p/3475773.html