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

    抠细节的题,题目思想如下:to implement the rotation in layers, if size is n, so there will be (int)(n / 2) layers that should be rotated. 

    需要注意的是:在下面这段code里面,需要注意的是:每一层layer中 i 的取值范围是 0<= i < m - layer - 1,注意上限是m-layer-1, 不是m-layer,如果是m-layer,就会多移。。造成意想不到的结果

     1 public class Solution {
     2     public void rotate(int[][] matrix) {
     3         int m = matrix.length;
     4         if (m == 0) return; 
     5         for (int layer = 0; layer < m / 2; layer++) {
     6             for (int i = layer; i < m - layer - 1; i++) {
     7                 int temp = matrix[layer][i]; //store up elements
     8                 matrix[layer][i] = matrix[m-1-i][layer]; // up is substituted by left
     9                 matrix[m-1-i][layer] = matrix[m-1-layer][m-1-i]; // left is substituted by down
    10                 matrix[m-1-layer][m-1-i] = matrix[i][m-1-layer]; // down is substitued by right
    11                 matrix[i][m-1-layer] = temp; // right is substituted by stored elements
    12             }
    13         }
    14     }
    15 }

    Another solution from Leetcode discussion

     1 /*
     2  * clockwise rotate
     3  * first reverse up to down, then swap the symmetry 
     4  * 1 2 3     7 8 9     7 4 1
     5  * 4 5 6  => 4 5 6  => 8 5 2
     6  * 7 8 9     1 2 3     9 6 3
     7 */
     8 void rotate(vector<vector<int> > &matrix) {
     9     reverse(matrix.begin(), matrix.end());
    10     for (int i = 0; i < matrix.size(); ++i) {
    11         for (int j = i + 1; j < matrix[i].size(); ++j)
    12             swap(matrix[i][j], matrix[j][i]);
    13     }
    14 }
  • 相关阅读:
    no-useless-call (Rules) – Eslint 中文开发手册
    Java 8 Stream
    CSS3 ,checked 选择器
    MySQL 数据类型
    _Alignas (C keywords) – C 中文开发手册
    C 库函数 – modf()
    JavaScript E 属性
    SyntaxError.prototype (Errors) – JavaScript 中文开发手册
    swagger和openAPI: 上传文件
    Java中HashMap的putAll()方法: HashMap.putAll()
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3794338.html
Copyright © 2011-2022 走看看