Python solution with algorithm faster than the most vote.

  • 0

    the idea is to go from outer layer to more inside layers.
    for example, if matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], the outermost layer is comprised of 1,2,3,4,8,12,16,15,14,13,9,5; the inside layer is 6,7,11,10; etc.
    This method is actually more efficient than the 'first reverse up to down, then swap the symmetry' method because no element will swapped more than once.

    class Solution(object):
        def rotate(self, matrix):
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            n = len(matrix)
            for i in xrange(n/2):
                for j in xrange(i,n-1-i):
                    temp = matrix[i][j]
                    matrix[i][j] = matrix[n-1-j][i]
                    matrix[n-1-j][i] = matrix[n-1-i][n-1-j]
                    matrix[n-1-i][n-1-j] = matrix[j][n-1-i]
                    matrix[j][n-1-i] = temp

Log in to reply

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