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

    开始做的时候使用了额外的matrix同等大小的空间,不属于inplace 的方案,通过看discuss, 看到如下通过两步可以做到inplace 的方案顺时针旋转90度,代码如下:

    public class Solution {//inplace solution
        public void rotate(int[][] matrix) {
            int n=matrix.length;
            int mid=n/2;
            //上下对折交换
            //1,2,3     7,8,9
            //4,5,6 ——> 4,5,6
            //7,8,9     1,2,3
            for(int i=0;i<mid;i++)
            {
                for(int j=0;j<n;j++)
                {
                    int temp=matrix[i][j];
                    matrix[i][j]=matrix[n-1-i][j];
                    matrix[n-1-i][j]=temp;
                }
            }
            //按对角线交换
            //7,8,9     7,4,1
            //4,5,6 ——> 8,5,2
            //1,2,3     9,6,3
            for(int i=0;i<n;i++)
            {
                for(int j=i;j<n;j++)
                {
                    int temp=matrix[i][j];
                    matrix[i][j]=matrix[j][i];
                    matrix[j][i]=temp;
                }
            }
        }
    }


  • 相关阅读:
    spring mvc poi excel
    select onchange事件的使用
    eclipse下svn的分支与合并指南
    jquery_final
    ListView
    资源的使用
    Notification
    单选
    复选框
    调试
  • 原文地址:https://www.cnblogs.com/eva_sj/p/6172258.html
Copyright © 2011-2022 走看看