302. Smallest Rectangle Enclosing Black Pixels
這道題有點意思,其實每一行或者每一列都是那個rotate sorted array II的變種,就是說有重復元素。不過因為給出了其中的一個點,那么就可以拿這個點做為分界線,去找四周的框。
class Solution(object):
def minArea(self, image, x, y):
"""
:type image: List[List[str]]
:type x: int
:type y: int
:rtype: int
"""
top = self.search_up(image, 0, x)
bottom = self.search_down(image, x, len(image)-1)
left = self.search_left(image, 0, y)
right = self.search_right(image, y, len(image[0])-1)
#print top, bottom, left, right
return (right - left+1) * (bottom - top+1)
def search_up(self, image, start, end):
while start + 1 < end:
mid = (start + end) / 2
if "1" in image[mid]:
end = mid
else:
start = mid
if "1" in image[start]:
return start
else:
return end
def search_down(self, image, start, end):
while start + 1 < end:
mid = (start + end) / 2
if "1" in image[mid]:
start = mid
else:
end = mid
if "1" in image[end]:
return end
else:
return start
def search_left(self, image, start, end):
while start + 1 < end:
mid = (start + end) / 2
if "1" in [row[mid] for row in image]:
end = mid
else:
start = mid
if "1" in [row[start] for row in image]:
return start
else:
return end
def search_right(self, image, start, end):
while start + 1 < end:
mid = (start + end) / 2
if "1" in [row[mid] for row in image]:
start = mid
else:
end = mid
if "1" in [row[end] for row in image]:
return end
else:
return start