zoukankan      html  css  js  c++  java
  • LeetCode 48. Rotate Image

    原题链接在这里:https://leetcode.com/problems/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[i][j] 由 matrix[n-1-j][i]替换.

    若是需要做成in-space, 那么相当于把矩阵拆成四块,第一块值保留,然后四块依次赋值,最后一块等于保留值。

    但需要注意循环中i,j中必有一个参数是小于等于Math.ceil(n/2.0), 否则中间点没有改值.

    Time Complexity: O(m*n). Space: O(1).

    AC Java:

     1 public class Solution {
     2     public void rotate(int[][] matrix) {
     3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
     4             return;
     5         }
     6         int n = matrix.length;
     7 
     8         for(int i = 0; i<n/2; i++){
     9             for(int j = 0; j<Math.ceil(n/2.0); j++){ //注意 2 要换成 double型, 2.0
    10                 int temp = matrix[i][j];
    11                 matrix[i][j] = matrix[n-1-j][i];
    12                 matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
    13                 matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
    14                 matrix[j][n-1-i] = temp;
    15             }
    16         }
    17     }
    18 }
  • 相关阅读:
    ehcache 使用
    android 换肤 apk
    ant 打不同渠道包
    strawberry perl
    rest 网络设计开发,降低复杂性设计方案
    android 进度条
    android 算定义布局xml
    ant 自动打包
    c# 调用cmd 输出 阻塞 解决
    web service2
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4841831.html
Copyright © 2011-2022 走看看