AC Python 32ms solution


  • 19
    def spiralOrder(self, matrix):
        if not matrix or not matrix[0]:
            return []
        ans = []
        m, n = len(matrix), len(matrix[0])
        u, d, l, r = 0, m - 1, 0, n - 1
        while l < r and u < d:
            ans.extend([matrix[u][j] for j in xrange(l, r)])
            ans.extend([matrix[i][r] for i in xrange(u, d)])
            ans.extend([matrix[d][j] for j in xrange(r, l, -1)])
            ans.extend([matrix[i][l] for i in xrange(d, u, -1)])
            u, d, l, r = u + 1, d - 1, l + 1, r - 1
        if l == r:
            ans.extend([matrix[i][r] for i in xrange(u, d + 1)])
        elif u == d:
            ans.extend([matrix[u][j] for j in xrange(l, r + 1)])
        return ans
    
    
    # 22 / 22 test cases passed.
    # Status: Accepted
    # Runtime: 32 ms
    # 100%

  • 0
    L

    @dietpepsi Probably more ideal to use append vs extend in a situation like this.

    Edit: Surprisingly comes out to the same run time even though extend is a o(k) operation


Log in to reply
 

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