题目来源:
https://leetcode.com/problems/rotate-image/
自我感觉难度/真实难度:hard 写题时间时长:1h
题意:
旋转一个矩阵
分析:
我自己打算用旋转最外圈的元素来实现旋转,内圈也是。但是这样很容易出错,对圈数和行数之间的关系,很容易出错
自己的代码:
class Solution: def rotate(self, m: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ length=len(m) n_loop=length//2 for i in range(n_loop): new_len=length-i*2 for _ in range(1,new_len-1): templ=m[i][i] for j in range(1,new_len): m[i+j-1][i]=m[i+j][i] for j in range(1,new_len): m[length-i-1][i+j-1]=m[length-i-1][i+j] for j in range(1,new_len): m[length-i-j][length-i-1]=m[length-i-j-1][length-i-1] for j in range(1,new_len): m[i][length-i-j]=m[i][length-i-j-1] m[i][i+1]=templ return
代码效率/结果:
优秀代码:
class Solution: def rotate(self, A): A.reverse() for i in range(len(A)): for j in range(i): A[i][j], A[j][i] = A[j][i], A[i][j]
代码效率/结果:
自己优化后的代码:
class Solution: def rotate(self, m: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ length=len(m) n_loop=length//2 for i in range(n_loop): m[i],m[length-1-i]=m[length-1-i],m[i] for row in range(length): for colum in range(row,length): m[row][colum],m[colum][row]=m[colum][row],m[row][colum] return
反思改进策略:
1.学习了一个骚操作~
自己的总结: 原来的数字,加一个负号,再左移一位。(或关于-1/2对称)
应用场景:在矩阵一头一尾操作时,可以使用,更加简洁
2.解题思路很关键,挖掘解题思路