LeetCode 48. Rotate Image(旋转图像)

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?

 


题目标签:Array

  这道题目给了我们一个n * n的矩阵,让我们旋转图片。题目要求in-place,所以就不能用额外的空间了。一开始自己写了一个很原始的方法,结果虽然通过,但是速度太慢。只好去看看别人的方法,看完觉得,自己以前数学课学的东西都还给老师了。来分析一下题目,举一个例子

1  2  3           1  4  7           7  4  1

4  5  6           2  5  8           8  5  2

7  8  9           3  6  9           9  6  3        

第一步,根据红色的对角线,找对应位置,互换两个数字的值。

第二步,对每一行数字,根据中线左右翻转。

 

Java Solution:

Runtime beats 61.89% 

完成日期:07/17/2017

关键词:Array

关键点:先逆矩阵再根据中线左右翻转每一行

                    

 1 public class Solution 
 2 {
 3     public void rotate(int[][] matrix) 
 4     {
 5         int n = matrix.length;
 6         
 7         // along the left top to right bottom diagonal line, swap symmetrical pair
 8         for(int i=0; i<n; i++) // for each row
 9         {
10             for(int j=i+1; j<n; j++) // for each number
11             {
12                 // swap the pair
13                 int temp = matrix[i][j];
14                 matrix[i][j] = matrix[j][i];
15                 matrix[j][i] = temp;
16             }
17         }
18         
19         // flip each row horizontally 
20         for(int i=0; i<n; i++)
21         {
22             for(int j=0; j<n/2; j++)
23             {
24                 int temp = matrix[i][j];
25                 matrix[i][j] = matrix[i][n-1-j];
26                 matrix[i][n-1-j] = temp;
27                 
28             }
29         }
30     }
31 }

参考资料:

http://www.cnblogs.com/grandyang/p/4389572.html

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

posted @ 2017-07-18 11:36  Jimmy_Cheng  阅读(1852)  评论(0编辑  收藏  举报