zoukankan      html  css  js  c++  java
  • 边工作边刷题: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"
    
    
  • 相关阅读:
    Asp.Net Mvc: 应用BindAttribute
    Mvc内建功能(DefaultModelBinder)自动绑定。
    生成随机字母字符串(数字字母混和)
    C#中实现输入汉字获取其拼音(汉字转拼音)的2种方法
    集合里查找数据
    C#自定义导出数据到Excel中的类封装
    MySQL性能优化的最佳20+条经验
    DevExpress.XtraGrid.view.gridview 属性说明
    c# 连接Mysql数据库
    ADO.NET 结构 集中数据库联接结构
  • 原文地址:https://www.cnblogs.com/absolute/p/5815814.html
Copyright © 2011-2022 走看看