zoukankan      html  css  js  c++  java
  • [LeetCode]: 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:找对应关系,90度翻转是:旧纵坐标->新横坐标  新纵坐标= 旧的横坐标的取反(最大高度-  旧的横坐标)

        public void rotate(int[][] matrix) {
            int[][] Temp = new int[matrix.length][matrix[0].length];
            for(int i = 0 ; i< matrix.length;i++){
                for(int j = 0 ; j< matrix.length;j++){
                    Temp[j][matrix.length-1-i] = matrix[i][j];
                }
            }
            
            for(int i = 0 ; i< matrix.length;i++){
                for(int j = 0 ; j< matrix.length;j++){
                    matrix[i][j] = Temp[i][j];
                }
            }
        }

    分析:这种结题方法使用了额外的存储空间!

    思路2:翻转+对折

    90度转换= 翻转(任意角度对角线翻转(撇捺向翻转):A[i][j] = A[j][i])+ 对折(上下或者左右翻转(横竖向翻转) :A[i][j] = A[i][length-1-j] )

    注意270度也是类似的思路

    推广:翻转180度= 翻转(任意角度对角线翻转:A[i][j] = A[j][i])

    代码:

        public void rotate(int[][] matrix) {
            
            //捺向翻转
            for(int i = 0 ; i< matrix.length;i++){
                for(int j = 0 ; j<i ;j++){
                    int Temp = matrix[i][j];
                    matrix[i][j] = matrix[j][i];
                    matrix[j][i] = Temp;
                }
            }
            
            //竖向翻转
            for(int i = 0 ; i< matrix.length;i++){
                for(int j = 0 ; j< matrix.length/2;j++){
                    int Temp = matrix[i][matrix.length-1-j];
                    matrix[i][matrix.length-1-j] = matrix[i][j];
                    matrix[i][j] = Temp;
                }
            }
        }
  • 相关阅读:
    asp.net mvc 缓存
    C#版 Socket编程(最简单的Socket通信功能)
    c# 读取嵌入式文件
    js 对象 copy 对象
    double截取小数点位数
    c#读取excel
    观察者设计模式
    xml序列化方式
    sicily Huffman coding
    sicily Fibonacci 2
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4878385.html
Copyright © 2011-2022 走看看