美文网首页
8.16 - hard - 58

8.16 - hard - 58

作者: 健时总向乱中忙 | 来源:发表于2017-08-17 00:33 被阅读0次

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

相关文章

  • 8.16 - hard - 58

    302. Smallest Rectangle Enclosing Black Pixels 这道题有点意思,其实...

  • 8.16 - hard - 61

    312. Burst Balloons 这种题型被总结为区间DP,一般用从终点朝起点去考虑会容易些,然后解法是记忆...

  • 8.16 - hard - 59

    305. Number of Islands II 一道union-find的题目,这类题目只要找准谁是boss就...

  • 8.16 - hard - 60

    308. Range Sum Query 2D - Mutable 这题所谓的标准解法是用segment tree...

  • 姨妈来

    8.16姨妈来

  • 平台经济

    交易成本 NP-hard问题 淘宝:货物 58同城:服务 B站:内容 算法是否让生活更美好? 算法是否影响了每一个...

  • 2018-08-31

    8.16 460 9.2 460 10.1 11.1

  • 19/09/2017

    Work hard,play hard,study hard, love hard.一个小姐姐跟我这么说。她说后两...

  • 英文书法练习~learning

    learning is sometimes hard, But hard is not impossible.学习...

  • 你辛苦了。

    Thanks for your hard work. 重读:hard

网友评论

      本文标题:8.16 - hard - 58

      本文链接:https://www.haomeiwen.com/subject/xenwrxtx.html