42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

 有很多种思路~

  1. 暴力解…算每个位置上下雨后可以装多高的水
  2. dp,把从左至右和从右至左最高的bar存起来
  3. 栈,我想到的直观思路
  4. 双指针,似乎是更快的思路,直观理解是,对于每一个位置i来说,其上的水量受制于左右两边最高的bar的最小的值(max-min),然后,区别与2那么暴力地去保存最高值,这边是通过双指针搜索的方式来获取。简单来说,就是不断更新左右两边的最高bar

 双指针的思路!!!增加一个左右两边的“壁垒”,思路很巧妙!

class Solution {
    public int trap(int[] height) {

        if(height.length == 0)return 0;
        int left = 0;
        int right = height.length - 1;
        int leftMax = height[left];
        int rightMax = height[right];
        int ret = 0;
        while(left < right){
            
            if(height[left] < height[right]){
                ret+=  Math.min(leftMax,rightMax) - height[left];
                left++;
                leftMax = Math.max(height[left],leftMax);
            }else{
                ret+= Math.min(rightMax,leftMax) - height[right];
                right--;
                rightMax = Math.max(height[right],rightMax);
            }
        }
        return ret;
    }
}

 栈的思路,核心难点在于恢复整个过程

class Solution {
    public int trap(int[] height) {
        Deque stack = new ArrayDeque<>();
        int ret = 0;
        
        for(int i = 0; i= height[i])stack.push(i++);
            else{
                int left = stack.pop();
                int add = stack.isEmpty()?
                    0: (Math.min(height[stack.peek()],height[i]) - height[left])*(i - stack.peek() - 1);
                ret+=add;
            }
        }
        
        return ret;
        
    }
}

你可能感兴趣的:(数据结构与算法,leetcode,数据结构与算法,算法)