[LeetCode][Java] Rotate Image

來源:互聯網
上載者:User

標籤:leetcode   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?

題意:

給定一個 n x n 的二維矩陣,來表示一副映像。

把映像旋轉90度(順時針)

你能否在原矩陣上完成呢?

演算法分析:

方法一:

空間複雜度較高,開闢額外的空間開複製原矩陣。但是最好理解

找到規律即可:matrix[j][l-i-1]=temmatrix[i][j];

temmatrix 這裡儲存的是原矩陣

方法二:

參考部落格http://pisxw.com/algorithm/Rotate-Image.html

基本思路是把圖片分為行數/2層,然後一層層進行旋轉,每一層有上下左右四個列,然後目標就是把上列放到右列,右列放到下列,下列放到左列,左列放回上列,中間儲存一個臨時變數即可。


AC代碼:

方法一:

public class Solution {    public void rotate(int[][] matrix)     {           int h = matrix.length;        int l = matrix[0].length;        int tem[][] = new int[h][l];        for(int i=0;i<h;i++)        {        for(int j=0;j<l;j++)        tem[i][j]=matrix[i][j];        }        for(int i=0;i<h;i++)        {        for(int j=0;j<l;j++)        {        matrix[j][l-i-1]=tem[i][j];        }        }            }}
方法二:
public class Solution {    public void rotate(int[][] matrix) {        if(matrix==null)            return;        int n=matrix.length-1;        for (int i = 0; i <= n/2; ++i)            {                for (int j = i; j < n-i; ++j)                {                    int tmp = matrix[i][j];                    matrix[i][j] = matrix[n-j][i];                    matrix[n-j][i] = matrix[n-i][n-j];                    matrix[n-i][n-j] = matrix[j][n-i];                    matrix[j][n-i] = tmp;                }            }        }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] Rotate Image

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.