0048. 旋转图像 #19
Replies: 11 comments 4 replies
-
|
致初学者: |
Beta Was this translation helpful? Give feedback.
-
|
请问为啥这里不需要一个中间变量存储matrix[i][j]也可以正常运行 |
Beta Was this translation helpful? Give feedback.
-
|
思路一基础思路不难,难的是后续能够写出来N+1,这玩意完全看运气 |
Beta Was this translation helpful? Give feedback.
-
|
补充一下为什么思路一是玄学,做对的偶然性很大 思路一(数学关系 + 演绎):
|
Beta Was this translation helpful? Give feedback.
-
|
思路二(数学关系 + 物理意义):
思路二难点在于有这样的数学直觉,其实说白了也是看经验。现在越来越感觉,计算机刷题的本质就是在积攒经验,到不至于说是背题,而是背诵遇到过的各种关键点(比如常见的双指针,不常见的如本题)。 |
Beta Was this translation helpful? Give feedback.
-
|
是不是有点写错了,文字写【水平翻转】但代码是竖直翻转。要么先转置再水平翻转,要么先竖直翻转再转置 |
Beta Was this translation helpful? Give feedback.
-
|
用嵌套列表推导式 |
Beta Was this translation helpful? Give feedback.
-
matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
n = len(matrix)
res = [[0] * n for _ in range(n)]
for i in range(n-1, -1, -1):
for j in range(-1,n):
res[j][n-i-1] = matrix[i][j]
print(res) |
Beta Was this translation helpful? Give feedback.
-
|
不怕诸位笑话,我一个老码工居然想了一个小时…… |
Beta Was this translation helpful? Give feedback.
-
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range (0,n):
for j in range(i,n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
matrix[i].reverse()
return matrix |
Beta Was this translation helpful? Give feedback.
-
|
题目的意思就是将一个二维数组进行水平翻转,从实现角度来看就是将一个下标的元素移动到另一个下标,先尝试找一下规律: 翻转之后原来下标的新位置应该是这样: 来看一下规律,以第一个点为例,移动过程如下: 第一个点 单独看并没有发现规律,交替一下来看,可以很容易发现规律。目标点的i就是当前的j,即当前元素的列号就是目标位置的行号;目标位置的j与当前位置的i呈现反序列额关系,即j = n - 1 - i。将这个规律带入其他点运算一下发现都满足,因此代码可以这样写(Python还不会,用C++代替一下): for(int i = 0; i < n; i++)
{
for(int j = i; j < n - i - 1; j++)
{
int temp = arr[n - 1 - j][i];
arr[n - 1 - j][i] = arr[n - 1 - i][n - 1 - j];
arr[n - 1 - i][n - 1 - j] = arr[j][n - 1 - i];
arr[j][n - 1 - i] = arr[i][j];
arr[i][j] = temp ;
}
}这样计算就相当于从外向内逐个圈的翻转,因此内层循环的次数要逐个减少,还要注意内层循环的 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
0048. 旋转图像 | 算法通关手册
https://algo.itcharge.cn/solutions/0001-0099/rotate-image/
Beta Was this translation helpful? Give feedback.
All reactions