LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目:

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) 把matrix想象成四塊,把第一塊摳出來並copy一份,然後旋轉式copy,代碼較長。

package rotation;public class RotateImage {    public void rotate(int[][] matrix) {        int n = matrix.length;        int rows = n / 2;        int cols = n % 2 == 0 ? rows : (rows + 1);        int[][] tmp = new int[rows][cols];        for (int i = 0; i < rows; ++i) {            for (int j = 0; j < cols; ++j) {                tmp[i][j] = matrix[i][j];            }        }                for (int i = rows; i < n; ++i) {            for (int j = 0; j < cols; ++j) {                matrix[j][n - 1 - i] = matrix[i][j];            }        }                for (int i = cols; i < n; ++i) {            for (int j = rows; j < n; ++j) {                matrix[j][n - 1 - i] = matrix[i][j];            }        }                for (int i = 0; i < cols; ++i) {            for (int j = cols; j < n; ++j) {                matrix[j][n - 1 - i] = matrix[i][j];            }        }                for (int i = 0; i < rows; ++i) {            for (int j = 0; j < cols; ++j) {                matrix[j][n - 1 - i] = tmp[i][j];            }        }    }        public static void main(String[] args) {        // TODO Auto-generated method stub        // int[][] matrix = {{1,2,3},{5,6,7},{9,10,11}};        int[][] matrix = {{1,2},{3,4}};        RotateImage r = new RotateImage();        r.rotate(matrix);    }}

2) 其實可以將上面的代碼進行簡化合并,如下

package rotation;public class RotateImage {    public void rotate(int[][] matrix) {        int n = matrix.length;        int rows = n / 2;        int cols = n - rows;        for (int i = 0; i < rows; ++i) {            for (int j = 0; j < cols; ++j) {                int tmp = matrix[i][j];                matrix[i][j] = matrix[n - 1 - j][i];                matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];                matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];                matrix[j][n - 1 - i] = tmp;            }        }    }        public static void main(String[] args) {        // TODO Auto-generated method stub        // int[][] matrix = {{1,2,3},{5,6,7},{9,10,11}};        int[][] matrix = {{1,2},{3,4}};        RotateImage r = new RotateImage();        r.rotate(matrix);    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.