美文网首页
42. 接雨水【dp】【朴素想法】

42. 接雨水【dp】【朴素想法】

作者: gykimo | 来源:发表于2021-07-23 00:01 被阅读0次

    题目:https://leetcode-cn.com/problems/trapping-rain-water/
    给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

    我的方法一:双指针

    步骤

    虽然官方解法也是双指针,但是明显官方的解法的更简洁,所以主要看看官方的方法,https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode-solution-tuvc/

    class Solution {
    public:
        int trap(vector<int>& height) {
            int ans = 0;
            int left = 0, right = height.size() - 1;
            int leftMax = 0, rightMax = 0;
            while (left < right) {
                leftMax = max(leftMax, height[left]);
                rightMax = max(rightMax, height[right]);
                if (height[left] < height[right]) {
                    ans += leftMax - height[left];
                    ++left;
                } else {
                    ans += rightMax - height[right];
                    --right;
                }
            }
            return ans;
        }
    };
    

    我的解法麻烦

    class Solution {
    public:
        int trap(vector<int>& height) {
            if(height.size()<3){
                return 0;
            }
    
            int sum = 0;
            int left = 0;
            int right = height.size()-1;
            int left_height=0;
            int right_height=0;
            int lower_height;
            int scanned_height=0;
            while(left<right){
                left_height = height[left];
                right_height = height[right];
                lower_height = left_height<right_height?left_height:right_height;
    
                if(lower_height<=scanned_height){
                    if(left_height>right_height){
                        right--;
                    }else{
                        left++;
                    }
                    continue;
                }
    
                for(int i = left+1; i<right; i++){
                    if(height[i]<lower_height){
                        if(height[i]>=scanned_height){
                            sum += lower_height-height[i];
                        }else{
                            sum += lower_height-scanned_height;
                        }
                    }
                }
    
                if(left_height>right_height){
                    right--;
                }else{
                    left++;
                }
                scanned_height=lower_height;
            }
    
            return sum;
        }
    };
    

    我的方法二:动态规划

    相关文章

      网友评论

          本文标题:42. 接雨水【dp】【朴素想法】

          本文链接:https://www.haomeiwen.com/subject/zxfumltx.html