zoukankan      html  css  js  c++  java
  • leetcode 48 Rotate Image ---- java

    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?

    题目意思很简单,就是给一个n*n的数组,然后将这个数组顺时针旋转90度,然后就是要求在有限的空间下进行。

    观察之后其实很简单,但是难在变量的控制上。修改了好几次才修改成功。

     

    如图所示,所替换的数字顺序就是:最外面一圈的顺序是:

                      1 --> 5 --> 25 --> 21 --> 1

                    2 --> 10 --> 24 --> 16 --> 2

                    3 --> 15 --> 23 --> 11 --> 3

                    4 --> 20 --> 22 --> 6 --> 4

    第二圈的顺序是:

                    7 --> 9 -->19 --> 17 -->7

                    8 --> 14 --> 18 --> 12 --> 8

    第三圈的顺序就是:

                    13本身不用变

    所以原理就是从外向里,一圈一圈的转90度。

    在这里就是第一圈代码好写,往里面写的时候,出错了好多次。但是理清思路,还是可以写好的。        

    结果是0ms。

    public class Solution {
        public void rotate(int[][] matrix) {
            int len = matrix[0].length;
            if( len < 2)
            	return ;
            int time = len/2,pos = len;
            for( int i = 0;i<time ;i++){
                pos--;
                //System.out.println(pos);
            	for( int j = i,k = 0;k<len-1;k++,j++){
            	    int num = matrix[i][j];
            		matrix[i][j] = matrix[pos-j+i][i];
            		matrix[pos-j+i][i] = matrix[pos][pos-j+i];
            		matrix[pos][pos-j+i] = matrix[j][pos];
            		matrix[j][pos] = num;
            	}
               	len-=2;
    
            	
            }
        }
    }
    
  • 相关阅读:
    关于QTTabBar的使用
    Delay, Sleep, Pause, & Wait in JavaScript
    highly recommended javascript books
    How to get the current script element
    MDX格式的字典制作
    while循环体的新用法
    printf函数的标准表达式
    C语言生成随机数代码
    C语言数组代码,小明摘苹果
    几个简单常用的C语言函数
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5707321.html
Copyright © 2011-2022 走看看