• 边工作边刷题: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<high:
            		if check(mid):
            			high = mid
            		else:
            			low = mid+1
            		mid = low + (high-low)/2
            	return mid
            
            top = binary(image, 0, x, lambda x: '1' in image[x])
            down = binary(image, x+1, len(image), lambda x: '1' not in image[x])
            left = binary(image, 0, y, lambda y: '1' in [row[y] for row in image])
            right = binary(image, y+1, len(image[0]), lambda y: '1' not in [row[y] for row in image])
            return (right-left)*(down-top)
    
    sol = Solution()
    assert sol.minArea([['0','0','1','0'], ['0','1','1','0'], ['0','1','0','0']], 0,2)==6, "must be 6"
    
    
  • 相关阅读:
    Javascript:三个函数ceil()、floor()、round()的区别
    一次搞懂建模语言UML
    firewalld 指定IP访问某端口
    Java通过图片url地址获取图片base64位字符串的两种方式
    个人笔记 截止2013.05.08
    解决ie6、7 marginbottom 失效问题
    jQuery 初学
    大小不固定的图片和多行文字的垂直水平居中(转)
    border :before :after 的应用
    关于<pre></pre>标签 IE6,7下实现whitespace:prewrap;
  • 原文地址:https://www.cnblogs.com/absolute/p/5815814.html
Copyright © 2020-2023  润新知