美文网首页
8.21 - hard - 79

8.21 - hard - 79

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

407. Trapping Rain Water II

利用外围边界,依次朝里面找,只是新加入heap的值需要取其原来值和新值比较高的那个点作为高度。

class Solution(object):
    def trapRainWater(self, heightMap):
        """
        :type heightMap: List[List[int]]
        :rtype: int
        """
        if not heightMap:
            return 0
        # 利用heap来做
        visited = [[False for _ in range(len(heightMap[0]))] for _ in range(len(heightMap))]
        
        # init
        heap = []
        for i in range(len(heightMap)):
            for j in range(len(heightMap[0])):
                if i == 0 or i == len(heightMap) - 1 or j == 0 or j == len(heightMap[0]) - 1:
                    heapq.heappush(heap, [heightMap[i][j], i, j])
                    visited[i][j] = True
        
        # find the lowest one
        res = 0
        while heap:
            cur, i, j = heapq.heappop(heap)
            for x, y in [[i+1, j], [i-1, j], [i, j+1], [i, j-1]]:
                if 0 <= x < len(heightMap) and 0 <= y < len(heightMap[0]) and not visited[x][y]:
                    res += max(0, cur - heightMap[x][y])
                    heapq.heappush(heap, [max(cur, heightMap[x][y]), x, y])
                    visited[x][y] = True
        
        return res

相关文章

  • 8.21 - hard - 79

    407. Trapping Rain Water II 利用外围边界,依次朝里面找,只是新加入heap的值需要取其...

  • 8.21 - hard - 74

    358. Rearrange String k Distance Apart 这道题就是把所有值都进行最大区分,在...

  • 8.21 - hard - 80

    410. Split Array Largest Sum 有两种解法: 按值二分: 左边界是array里的最大值,...

  • 8.21 - hard - 72

    352. Data Stream as Disjoint Intervals 有序的几个重要数据结构和算法:hea...

  • 8.21 - hard - 73

    354. Russian Doll Envelopes 简单的DP的话,会TLE,worst case O(n^2...

  • 8.21 - hard - 75

    363. Max Sum of Rectangle No Larger Than K 如果是求最大值,用for l...

  • 8.21 - hard - 76

    381. Insert Delete GetRandom O(1) - Duplicates allowed 设计...

  • 8.21 - hard - 77

    391. Perfect Rectangle 找出四个边角点。 所有的小矩形面积和等于大矩形面积 除了四个边角点,...

  • 8.21 - hard - 78

    403. Frog Jump首先做出来一个TLE的版本,因为这里面要search三种情况,可以用记忆化搜索来做。

  • 我的生日,不想和任何人分享

    8.21

网友评论

      本文标题:8.21 - hard - 79

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