Sunday, August 16, 2015

Leetcode 48. Rotate Image

https://leetcode.com/problems/rotate-image/

First perform a transposition, then reverse every row.
1    2             1    3              3    1
3    4    =>     2    4    =>      4    2

Solution:
# T:O(n^2) S:O(1)
class Solution:
    # @param {integer[][]} matrix
    # @return {void} Do not return anything, modify matrix in-place instead.
    def rotate(self, matrix):
        n = len(matrix)
        for i in xrange(n):
            for j in xrange(i+1, n):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
                # get transposition
        for i in xrange(n):
            matrix[i].reverse()
        return
Run Time: 56 ms

No comments:

Post a Comment