首页 > 其他 > 详细

leetcode------Rotate Image

时间:2015-03-07 17:01:38      阅读:211      评论:0      收藏:0      [点我收藏+]
标题: Rotate Image
通过率: 31.7%
难度: 中等

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?

这个题目想了好久想不出来,能找出来规律就是做不出来,最后参考了网上的代码和思路:

就是一个2Dmatrix中每个元素都要向右移动N-1次,只用对半移动然后是一层一层的移动,

1 2 3
4 5 6
7 8 9

1-》3-》9-》7-》1

2-》6-》8-》4-》2

上述是第一层第二层只有5不用移动

一次类推

所以移动的层数等于数组的层数除以2,

不管N是个多大的数字,每一层额每一个位置都是四个数字的转换,这就有了规律

具体看代码:

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         int len=matrix.length;
 4         for(int round=0;round<len/2;round++){
 5             int i=round;
 6             for(int j=i;j<len-round-1;j++){
 7                 int tmp=matrix[i][j];
 8                     int temp = matrix[i][j];
 9                     matrix[i][j] = matrix[len-j-1][i];
10                     matrix[len-j-1][i] = matrix[len-i-1][len -j -1];
11                     matrix[len-i-1][len -j -1] = matrix[j][len - i -1];
12                     matrix[j][len - i -1] = temp;
13                 
14             }
15         }
16     }
17 }

 

leetcode------Rotate Image

原文:http://www.cnblogs.com/pkuYang/p/4320490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!