zoukankan      html  css  js  c++  java
  • LeetCode OJ 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?


    【题目解析】

    这个题目的要求是把一个二维数组向右旋转九十度,就地实现。


    【思路1】

    相比较矩阵的转置,矩阵的旋转有什么不同呢?看下面的例子:

    1,2,3          1,3,2      1,2,3          2,3,1 

    3,2,1    ----转置--->   2,2,3  3,2,1    ----旋转--->   3,2,2

    2,3,1          3,1,1  2,3,1          1,1,3

    观察上面的结果我们发现这两个不同操作的结果是不同的,但是又有一定的关系,即转置后的每一行是旋转后每一行的逆序。如果就地实现旋转的话,我们发现这是有一定难度的——最后一列变为第一行,倒数第二行变为第二列······,如果我们先转置再逆序的话是很容易实现的。


     【思路2】


    【java代码1】

     1 public class Solution {
     2     public void rotate(int[][] matrix) {
     3         int row = matrix.length;
     4         if(row == 0) return;
     5         int col = matrix[0].length;
     6         if(col < row) return;
     7         
     8         for(int i = 0; i < row; i++){
     9             for(int j = i + 1; j < row; j++){
    10                 int temp = matrix[i][j];
    11                 matrix[i][j] = matrix[j][i];
    12                 matrix[j][i] = temp;
    13             }
    14             for(int k = 0, m = row - 1; k < m; k++, m--){
    15                 int temp = matrix[i][k];
    16                 matrix[i][k] = matrix[i][m];
    17                 matrix[i][m] = temp;
    18             }
    19         }
    20     }
    21 }

     【代码2】

     1 class Solution {
     2 public:
     3     void rotate(vector<vector<int> > &matrix) {
     4         int i,j,temp;
     5         int n=matrix.size();
     6         for(i = 0;i < n/2;++i) {
     7             for (j = i;j < n-1-i;++j) {
     8                 temp = matrix[j][n-i-1];
     9                 matrix[j][n-i-1] = matrix[i][j];
    10                 matrix[i][j] = matrix[n-j-1][i];
    11                 matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
    12                 matrix[n-i-1][n-j-1] = temp;
    13             }//for
    14         }//for
    15     }
    16 };
  • 相关阅读:
    NSString
    xib和storyboard的使用方法
    drawRect画线和使用CGContext
    CGAffineTransform动画
    【概念】静态成员
    【c#】Application.Exit和Close有什么不同
    【c#】const和readonly关键字
    【概念】设计模式
    【概念】常见数据结构与算法
    【概念】索引器
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5527084.html
Copyright © 2011-2022 走看看