zoukankan      html  css  js  c++  java
  • 接雨水

    题目如下:

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

     代码如下:

    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
     
  • 相关阅读:
    3.1 history跳转页面产生跨域问题
    2021年6月7日 团队冲刺第二阶段04
    2021年6月6日 团队冲刺第二阶段03
    2021年6月5日 团队冲刺第二阶段02
    2021年6月4日 团队冲刺第二阶段01
    2021年6月3日
    2021年6月2日
    2021年6月1日
    2021年5月31日
    2021年5月30日
  • 原文地址:https://www.cnblogs.com/tsdblogs/p/12348130.html
Copyright © 2011-2022 走看看