5

[leetcode]旋转矩阵

 1 year ago
source link: https://www.okayjam.com/leetcode%E6%97%8B%E8%BD%AC%E7%9F%A9%E9%98%B5/
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]旋转矩阵

Posted on 2022年6月30日

[leetcode]旋转矩阵

给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。

不占用额外内存空间能否做到?

示例 1:

给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

示例 2:

给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

两个思路:
1、通过观察可以发现, 旋转后的矩阵和原矩阵有一定的关联: 原来的第i行变成了旋转后的第n-i-1列,因此通过这样的方法,可以确定一个新的矩阵,两个for循环赋值即可,但是这个方法需要额外的矩阵空间

2、在旋转的过程中,每一圈都是可以找到对应的赋值规律的,先处理外圈,然后处理内圈,之前把所有的 圈处理。旋转主要是处理4个边的原始,依此赋值即可

func rotate(matrix [][]int) {
    l1 := len(matrix)
    for i := 0; i < l1/2; i++ {
        for j := i; j < l1-i-1; j++ {
            f := matrix[j][l1-i-1]
            matrix[j][l1-i-1] = matrix[i][j]
            //f2 := matrix[l1-j-1][l1 -i -j]
            //matrix[l1-j-1][l1 -i -j] = f
            matrix[i][j] = matrix[l1-j-1][i]
            matrix[l1-j-1][i] = matrix[l1-i-1][l1-j-1]
            matrix[l1-i-1][l1-j-1] = f
        }
    }
}

欢迎关注个人公众号

qrcode_for_gh_360d107cfcf8_344.jpg

This entry was posted in 技术 and tagged leetcode, 技术, 笔记. Bookmark the permalink.

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论 *

显示名称 *

电子邮箱地址 *

网站地址

在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK