Short Python in-place solution - 50ms


  • 1
    G
    class Solution:
        # @param matrix, a list of lists of integers
        # @return a list of lists of integers
        def rotate(self, matrix):
            matrix.reverse()
            for i in range(len(matrix)):
                for j in range(i):
                    matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

  • 0
    L

    Are you sure we are allowed to reverse()... Good observation though


  • 0
    G

    In terms of interview, you should be able to use .reverse() in most of the complex problem. Ofc you shouldn't use this in problems like reverse a string.

    It is always helpful to ask interviewer "can I use reverse() in this question? If not I can do the reverse by hand". If the interviewer says no, then you can easily change the matrix.reverse() into a helper function such as reverseMatrix(matrix):

    reverseMatrix(self, matrix):
        n = len(matrix)
        for i in n / 2:
            matrix[i], matrix[n - 1 - i] = matrix[n - 1 - i], matrix[i]
    
    or simply:
    reverseMatrix(self, matrix):
        matrix[:] = matrix[::-1]

  • 0
    L

    I think you are right. Thanks for the fast reply!


  • 0

    for i in n / 2:? Ts ts ts...


  • 0
    G

    for i in range(n / 2) :p


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.