4

Leetcode 48 旋转图像(Rotate Image) 题解分析

 2 years ago
source link: https://nicksxs.me/2021/05/01/Leetcode-48-%E6%97%8B%E8%BD%AC%E5%9B%BE%E5%83%8F-Rotate-Image-%E9%A2%98%E8%A7%A3%E5%88%86%E6%9E%90/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Leetcode 48 旋转图像(Rotate Image) 题解分析

Posted on

2021-05-01 In Java , leetcode , Rotate Image

Views: 7 Views: 11 Disqus: 0 Comments

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

如图,这道题以前做过,其实一看有点蒙,好像规则很容易描述,但是代码很难写,因为要类似于贪吃蛇那样,后来想着应该会有一些特殊的技巧,比如翻转等

public void rotate(int[][] matrix) {
        // 这里真的傻了,长宽应该是一致的,所以取一次就够了
        int lengthX = matrix[0].length;
        int lengthY = matrix.length;
        int temp;
        System.out.println(lengthY - (lengthY % 2) / 2);
        // 这里除错了,应该是减掉余数再除 2
//        for (int i = 0; i < lengthY - (lengthY % 2) / 2; i++) {
        /**
         * 1 2 3             7 8 9
         * 4 5 6     =>      4 5 6     先沿着 4 5 6 上下交换
         * 7 8 9             1 2 3
         */
        for (int i = 0; i < (lengthY - (lengthY % 2)) / 2; i++) {
            for (int j = 0; j < lengthX; j++) {
                temp = matrix[i][j];
                matrix[i][j] = matrix[lengthY-i-1][j];
                matrix[lengthY-i-1][j] = temp;
            }
        }

        /**
         * 7 8 9               7 4 1
         * 4 5 6     =>        8 5 2   这里再沿着 7 5 3 这条对角线交换
         * 1 2 3               9 6 3
         */
        for (int i = 0; i < lengthX; i++) {
            for (int j = 0; j <= i; j++) {
                if (i == j) {
                    continue;
                }
                temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }

还没到可以直接归纳题目类型的水平,主要是几年前做过,可能有那么点模糊的记忆,当然应该也有直接转的方法


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK