48、Rotate Image

90°旋转二维数组

解法1: 先以对角线为轴翻转得到其转置矩阵,再以中间竖轴翻转。

1  2  3      1  4  7      7  4  1

4  5  6 -->   2  5  8  -->  8  5  2  

7  8  9      3  6  9      9  6  3
解法2: 先以反对角线翻转,在以中间水平轴翻转。

1  2  3     9  6  3      7  4  1

4  5  6 -->   8  5  2  -->   8  5  2  

7  8  9      7  4  1      9  6  3

使用第一种解法

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
         
        // along the left top to right bottom diagonal line, swap symmetrical pair
        for(int i=0; i<n; i++) {  // for each row
            for(int j=i+1; j<n; j++) {  // for each number
                // swap the pair
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
         
        // flip each row horizontally
        for(int i=0; i<n; i++) {
            for(int j=0; j<n/2; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][n-1-j];
                matrix[i][n-1-j] = temp;
                 
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目 You are given an n x n 2D matrix representing an image...
    persistent100阅读 1,651评论 0 0
  • 题目描述:给一个n * n的二维数组表示的图片,将其原地顺时针旋转90度。如: Given input matri...
    Nautilus1阅读 1,755评论 0 0
  • 题目 You are given an n x n 2D matrix representing an image...
    Al73r阅读 1,625评论 0 0
  • 要想知道世界的安排 就去听听时间的独白 挑着鲜花的长刀,另一头 不是正流着鲜血? 眩目的红晕 一样...
    望北集阅读 1,124评论 1 7
  • 1 最近在追《恋爱先生》,里面的剧情迷住了。 一开始,剧情的确很狗血,在程皓和罗玥间不断地相遇,斗嘴,两人的情感也...
    糯米宁阅读 3,443评论 0 0