simple Python solution


  • 0
    W

    Time exceeded with Numpy,but it does work except that.

    import numpy as np 
    
    class Solution(object):
        def imageSmoother(self,M):
            """
            :type M: List[List[int]]
            :rtype: List[List[int]]
            """
            tmp=np.array(M)
            ret=[]
            (height,width)=tmp.shape
            for i in np.arange(height):
                ret_tmp=[]
                for j in np.arange(width):
                    ret_tmp.append(int(tmp[max(i-1,0):min(i+1,height-1)+1,max(j-1,0):min(j+1,width-1)+1].mean()))
                ret.append(ret_tmp)
            return ret
    

  • 0
    W

    same way without Numpy and it works! Maybe Numpy is slow to translate M to array when M is too big?

    class Solution(object):
        def average(self,M,xmin,xmax,ymin,ymax):
            Msum=0
            Mcount=0
            for i in range(xmin,xmax):
                for j in range(ymin,ymax):
                    Msum+=M[i][j]
                    Mcount+=1
            return int(Msum/Mcount)
    
        def imageSmoother(self,M):
            """
            :type M: List[List[int]]
            :rtype: List[List[int]]
            """
            ret=[]
            (height,width)=(len(M),len(M[0]))
            for i in range(height):
                ret_tmp=[]
                for j in range(width):
                    ret_tmp.append(self.average(M,max(i-1,0),min(i+1,height-1)+1,max(j-1,0),min(j+1,width-1)+1))
                ret.append(ret_tmp)
            return ret
    

Log in to reply
 

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