zoukankan      html  css  js  c++  java
  • 【leetcode】42. Trapping Rain Water

    题目如下:

    解题思路:我的方法是找出所有的顶点,即满足height[i] > height[i+1] && height[i] > height[i-1]条件的index,如果height[i] == height[i+1],则需要往后顺延,找到i后面第一个不与自己相等的点,把所有的顶点存入列表peaks,接下来遍历peaks,对于任意一个peaks[i],找出第一个j满足j > i && height[peaks[i]] > height[peaks[j]],这一个区间就是一个盛水区间,如果找不到相应的j,那么就找出height[peaks[i] -> end] 内height的最大值。找出所有盛水区间后,计算总量即可。

    代码如下:

    class Solution(object):
        def getNextPeak(self,inx,peaks,height):
            maxH = 0
            maxInx = 0
            for i in range(inx+1,len(peaks)):
                if height[peaks[inx]] <= height[peaks[i]]:
                    return i
                if maxH < height[peaks[i]]:
                    maxH = height[peaks[i]]
                    maxInx = i
            return maxInx
        def getNextNoDupHeightInx(self,inx,height):
            for i in range(inx,len(height)):
                if height[inx] != height[i]:
                    return i
            return -1
    def getPeaks(self, peaks, height): i = 0 while i < len(height): nextInx = self.getNextNoDupHeightInx(i, height) if nextInx == -1: if height[i] > height[i - 1]: peaks.append(i) break if i == 0 and height[i] > height[nextInx]: peaks.append(i) elif height[i] > height[i - 1] and height[i] > height[nextInx]: peaks.append(i) i = nextInx def trap(self, height): """ :type height: List[int] :rtype: int """ if len(height) < 3: return 0 peaks = [] self.getPeaks(peaks,height) print peaks res = 0 i = 0 while i < len(peaks)-1: nextInx = self.getNextPeak(i,peaks,height) high = min(height[peaks[i]],height[peaks[nextInx]]) for j in xrange(peaks[i],peaks[nextInx]): water = max(0,high - height[j]) res += water i = nextInx return res
  • 相关阅读:
    985的方格难题
    POJ 3264 区间最大最小值Sparse_Table算法
    oracle中to_date详细用法示例(oracle日期格式转换)
    PLSQL基础知识-图片
    oracle-查询-时间条件查询
    oracle基础函数--decode
    PLSQL基础学习-文字
    python3 MD5
    CentOS7关闭防火墙方法
    CentOS 7下源码安装MySQL 5.6
  • 原文地址:https://www.cnblogs.com/seyjs/p/9354680.html
Copyright © 2011-2022 走看看