码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Rotate Image

时间:2015-09-27 09:56:54      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/rotate-image/

顺时针旋转矩阵,举例子找规律。

若是需要做成in-space, 那么相当于把矩阵拆成四块,第一块值保留,然后四块依次赋值,最后一块等于保留值。但需要注意循环中i,j中必有一个参数是小于等于Math.ceil(n/2), 否则中间点没有改值。

AC Java:

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         /*
 4         //Method 1
 5         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
 6             return;
 7         }
 8         int n = matrix.length;
 9         int [][] newMatrix = new int[n][n];
10         
11         for(int i = 0; i<n; i++){
12             for(int j = 0; j<n; j++){
13                 newMatrix[j][n-1-i] = matrix[i][j];
14             }
15         }
16         for(int i = 0; i<n; i++){
17             for(int j = 0; j<n; j++){
18                 matrix[i][j] = newMatrix[i][j];
19             }
20         }
21         return;
22         */
23         //Method 2
24         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
25             return;
26         }
27         int n = matrix.length;
28         for(int i = 0; i<n/2; i++){
29             for(int j = 0; j<Math.ceil(n/2.0);j++){
30                 int temp = matrix[i][j];
31                 matrix[i][j] = matrix[n-1-j][i];
32                 matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
33                 matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
34                 matrix[j][n-1-i] = temp;
35             }
36         }
37     }
38 }

 

LeetCode Rotate Image

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4841831.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!