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
  • 相关阅读:
    ES6:Iterator遍历器
    前端:对BFC的理解
    前端:性能优化之防抖与节流
    ES6新增数据类型Symbol
    ajax和fetch、aixos的区别
    我对js数据类型的理解和深浅(copy)的应用场景
    egg的基本使用
    前端:css3的过渡与动画的基础知识
    Java基础篇之类
    JAVA基础篇之Scanner
  • 原文地址:https://www.cnblogs.com/seyjs/p/9354680.html
Copyright © 2011-2022 走看看