In-place computation beat 100% python solutions


  • 0
    R

    First, make M[i][j] to be the sum of M[i][j-1], M[i][j] and M[i][j+1],
    then, make M[i][j] to be the sum of M[i-1][j], M[i][j] and M[i+1][j],
    and finally with a right divisor ...

    class Solution(object):
        def imageSmoother(self, M):
            heigh = len(M)
            width = len(M[0])
            for i in range(heigh):
                prev = -1
                for j in range(width-1,-1,-1):
                    nextPrev = M[i][j]
                    M[i][j] += (0 if prev == -1 else prev) + \
                                (0 if j == 0 else M[i][j-1])
                    prev = nextPrev
            for j in range(width):
                prev = -1
                for i in range(heigh-1,-1,-1):
                    nextPrev= M[i][j]
                    M[i][j] += (0 if prev == -1 else prev) + \
                                (0 if i == 0 else M[i-1][j])
                    prev = nextPrev
            for i in range(heigh):
                for j in range(width):
                    count   = (0 if j == 0 else 1) + 1 + (0 if j == width-1 else 1)
                    divisor = (0 if i == 0 else count) +\
                              count + \
                              (0 if i == heigh-1 else count)
                    M[i][j] /= divisor
            return M
    

Log in to reply
 

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