zoukankan      html  css  js  c++  java
  • 【leetcode】Rotate Image

    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?

     
     
    假设旋转的时候,左上角元素为(l,l),右下角元素为(r,r)
    则旋转的时候
    (l,l+1)=(r-1,l) 最上面一排 
    (r-1,l)=(r,r-1)左边一排
    (r,r-1)=(l+1,r)下面一排
    (l+1,r)=(l,l+1)右边一排
     
    可以找到规律
    (i,j)--->(r+l-j,i)
     
     
     1 class Solution {
     2 public:
     3     void rotate(vector<vector<int> > &matrix) {
     4        
     5         int n=matrix.size();
     6         int leftUp=0;
     7         int rightBottom=n-1;
     8         while(rightBottom>leftUp)
     9         {
    10             int n0=rightBottom+leftUp;
    11             for(int i=leftUp;i<rightBottom;i++)
    12             {
    13                 int tmp=matrix[leftUp][i];
    14                 matrix[leftUp][i]=matrix[n0-i][leftUp];
    15                 matrix[n0-i][leftUp]=matrix[n0-leftUp][n0-i];
    16                 matrix[n0-leftUp][n0-i]=matrix[i][n0-leftUp];
    17                 matrix[i][n0-leftUp]=tmp;
    18  
    19             }
    20            
    21             leftUp++;rightBottom--;
    22         }
    23     }
    24 };
     
     
  • 相关阅读:
    java常见异常
    实现两个整数变量交换
    java抽象类与接口
    Java内部类用法
    单例模式
    easyUI下拉列表点击事件的使用
    Java中使用HttpRequest获取用户真实IP地址端口
    js-easyUI格式化时间
    1124
    ACM算法
  • 原文地址:https://www.cnblogs.com/reachteam/p/4214111.html
Copyright © 2011-2022 走看看