[leetcode-42]Trapping Rain Water(java)

问题描述:
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.
这里写图片描述

分析:我的解题思路是和图中的所示面积是相吻合的。这里面维护一个堆栈,如果当前元素大于栈顶元素,出栈,并在两个元素中维护一个面积数组。然后再进行完之后,处理一下余下的堆栈数据。然后再计算面积之和。

代码如下:344ms

public class Solution {
        public int trap(int[] height) {
        Stack<Integer> heightStack = new Stack<>();
        List<Integer> indexList = new LinkedList<>();
        int length = height.length;
        int[] area = new int[length];

        for(int i = 0;i<length;i++){
            if(heightStack.isEmpty()){
                heightStack.push(height[i]);
                indexList.add(i);
                continue;
            }
            int val = height[i];

            while(!heightStack.isEmpty()){
                int prev = heightStack.peek();
                if(val<prev)
                    break;

                int prevIndex = indexList.remove(indexList.size() - 1);
                for(int j = prevIndex+1;j<i;j++){
                    area[j] = prev-height[j];
                }
                heightStack.pop();
            }
            heightStack.push(val);
            indexList.add(i);
        }
        int head;
        int headIndex;

        while(!heightStack.isEmpty()){
            head = heightStack.pop();
            headIndex = indexList.remove(indexList.size()-1);

            if(heightStack.isEmpty())
                break;

            int peekIndex = indexList.get(indexList.size()-1);
            for(int i = headIndex-1;i>peekIndex;i--){
                area[i] = head-height[i];
            }
        }
        int count = 0;
        for(int i = 0;i<length;i++) {
            count += area[i];
        }
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值