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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM