首页 技术 正文
技术 2022年11月20日
0 收藏 952 点赞 4,637 浏览 1778 个字

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"
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289