Lonely PIxel I

如果两遍pass这个题完全可以利用一个行数组和一个列数组来记录各个B的位置,最后找行列都是1的位置加起来就行了,这样空间复杂度是O(n + m)

class Solution(object):
    def findLonelyPixel(self, picture):
        """
        :type picture: List[List[str]]
        :rtype: int
        """
        n = len(picture)
        if not n:
            return 0

        m = len(picture[0])
        if not m:
            return 0

        rowList, colList = [0] * n, [0] * m
        for i in xrange(n):
            for j in xrange(m):
                if picture[i][j] == 'B':
                    rowList[i] += 1
                    colList[j] += 1

        result = 0
        for i in xrange(n):
            for j in xrange(m):
                if picture[i][j] == 'B' and rowList[i] == 1 and colList[j] == 1:
                    result += 1
        return result

如果只使用单维数组,则我们需要用一个单独变量统计另外一维的B出现次数,然后每行进行一次统计,这样空间复杂度O(m)

class Solution(object):
    def findLonelyPixel(self, picture):
        """
        :type picture: List[List[str]]
        :rtype: int
        """
        n = len(picture)
        if not n:
            return 0

        m = len(picture[0])
        if not m:
            return 0

        colList = [0] * m
        for i in xrange(n):
            for j in xrange(m):
                if picture[i][j] == 'B':
                    colList[j] += 1

        result = 0
        for i in xrange(n):
            count = 0
            lastPosition = 0
            for j in xrange(m):
                if picture[i][j] == 'B':
                    count += 1
                    lastPosition = j
            if count == 1 and colList[lastPosition] == 1:
                result += 1
        return result

results matching ""

    No results matching ""