【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

 

posted @ 2018-07-23 14:59  seyjs  阅读(144)  评论(0编辑  收藏  举报