Skip to content

Latest commit

 

History

History
100 lines (93 loc) · 1.84 KB

48.md

File metadata and controls

100 lines (93 loc) · 1.84 KB

小知识

  • 使用zip和[::-1]旋转矩阵
>>> a
[[1, 2], [3, 4]]
>>> a[::-1]
[[3, 4], [1, 2]]
>>> b = []
>>> b[:] = zip(*a)
>>> b
[(1, 3), (2, 4)]
>>> b[:] = zip(*a[::-1])
>>> b
[(3, 1), (4, 2)]
>>>
  • list中的~用法:
>>> a = [1,2,3,4]
>>> a[-1]
4
>>> a[~1]
3
>>> a[~2]
2
>>>
其实就相当于a[~i] = a[len(a)-1-i]

解法一:

  • 32ms
  • 90%
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        matrix[:] = zip(*matrix[::-1])

解法二

class Solution:
    def rotate(self, A):
        n = len(A)
        for i in range(n/2):
            for j in range(n-n/2):
                A[i][j], A[~j][i], A[~i][~j], A[j][~i] = \
                         A[~j][i], A[~i][~j], A[j][~i], A[i][j]

解法三

class Solution:
    def rotate(self, A):
        A[:] = map(list, zip(*A[::-1]))

解法四

class Solution:
    def rotate(self, A):
        A[:] = [[row[i] for row in A[::-1]] for i in range(len(A))]

解法五

class Solution:
    def rotate(self, A):
        n = len(A)
        for i in range(n/2):
            for j in range(n-n/2):
                for _ in '123':
                    A[i][j], A[~j][i], i, j = A[~j][i], A[i][j], ~j, ~i
                i = ~j

解法六

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, A):
        n = len(A)
        for i in range(n):
            for j in range(i):
                A[i][j], A[j][i] = A[j][i], A[i][j]
        for row in A:
            for j in range(n/2):
                row[j], row[~j] = row[~j], row[j]