首页 > 其他 > 详细

接雨水

时间:2020-02-23 01:19:24      阅读:61      评论:0      收藏:0      [点我收藏+]

题目如下:

技术分享图片

 

 方法一:动态编程解题思路:

技术分享图片

 

 代码如下:

int trap(vector<int>& height)
{
    if(height == null)
        return 0;
    int ans = 0;
    int size = height.size();
    vector<int> left_max(size), right_max(size);
    left_max[0] = height[0];
    for (int i = 1; i < size; i++) {
        left_max[i] = max(height[i], left_max[i - 1]);
    }
    right_max[size - 1] = height[size - 1];
    for (int i = size - 2; i >= 0; i--) {
        right_max[i] = max(height[i], right_max[i + 1]);
    }
    for (int i = 1; i < size - 1; i++) {
        ans += min(left_max[i], right_max[i]) - height[i];
    }
    return ans;
}

方法二:双指针解题思路:

技术分享图片

 

 代码:

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left = 0
        right = len(height) - 1
        res = 0
        left_max = 0
        right_max = len(height) - 1

        while left < right:
            if height[left] > height[right]:
                if height[right_max] < height[right]:
                    right_max = right
                    right = right - 1
                else:
                    res += height[right_max] - height[right]
                    right = right - 1

            if height[left] <= height[right]:
                if height[left_max] < height[left]:
                    left_max = left
                    left = left + 1
                else:
                    res += height[left_max] - height[left]
                    left = left + 1
        return res

 

 

接雨水

原文:https://www.cnblogs.com/tsdblogs/p/12348130.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!