边工作边刷题:70天一遍leetcode: day 89-1

Smallest Rectangle Enclosing Black Pixels
要点:记题:这题有两个限制条件:所有black pixel是连通的(所以可以用binary search)以及给了一个black pixel。
错误理解:给定black pixel所在行/列的top/down/left/right是不正确的。因为这题为2d,二分的条件是一整行/列上是否有black pixel,也就是把整个行/列作为一个元素,而对应的列/行作为搜索array。给定的点只是作为low/high的初始条件

  • 二分是bounded binary search,类似First Bad Version,什么意思?就是二分搜索只有两部分,符合条件的是high end(因为>high的部分都符合)
    • top:对行二分(0和x之间),某一行有black pixel是high
    • bottom:同样对行二分(x到m),某一列没有black pixel是high
    • left:类似top:列二分(0到y之间),某一行有black pixel是high
    • right:类似bottom,对列二分(y到n),某一行没有black pixel是high
  • 为什么能统一code(just pass in check)?left/top搜索第一个1,right/bottom搜索第一个0,目标都是high end

https://repl.it/Cdja/5
错误点


- bounded binary search如果high为highest index+1,可以自动handle边界条件:如果找left,那么如果left不存在(比如这题全是0)。那么最终返回high。这是因为low==high是不会处理的,最后的mid是low==high的mid
- y轴如何写lambda?loop row,然后每个row[y] list comprehension就得到list了。也可以用any()/all()

# An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. Given the location (x, y) of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.

# For example, given the following image:

# [
#   "0010",
#   "0110",
#   "0100"
# ]
# and x = 0, y = 2,
# Return 6.


class Solution(object):
    def minArea(self, image, x, y):
        """
        :type image: List[List[str]]
        :type x: int
        :type y: int
        :rtype: int
        """
        def binary(image, low, high, check):
            mid = low + (high-low)/2
            while low

转载于:https://www.cnblogs.com/absolute/p/5815814.html

你可能感兴趣的:(边工作边刷题:70天一遍leetcode: day 89-1)