其他分享
首页 > 其他分享> > 【leetcode字节跳动题库】42. Trapping Rain Water

【leetcode字节跳动题库】42. Trapping Rain Water

作者:互联网

用个单调栈

提交代码

class Solution {
    public int trap(int[] height) {
    	Stack<Integer> hStack=new Stack<Integer>();
    	Stack<Integer> pStack=new Stack<Integer>();
    	
    	int hLeft=0,base=0,water=0;
    	
    	for(int i=0;i<height.length;i++) {
    		if(hStack.isEmpty()||hStack.peek()>height[i]) {
    			hStack.push(height[i]);
    			pStack.push(i);
    		}else {
    			while(!hStack.isEmpty()&&hStack.peek()<=height[i]) {
    				base=hStack.pop();
    				pStack.pop();
    				if(hStack.isEmpty())	break;
    				hLeft=hStack.peek();
    				water+=(Math.min(hLeft, height[i])-base)*(i-pStack.peek()-1);
    			}
    			hStack.push(height[i]);
    			pStack.push(i);
    		}
    	}
    	
    	return water;
    }
    
}

运行结果

在这里插入图片描述

AXIMI 发布了390 篇原创文章 · 获赞 27 · 访问量 7万+ 私信 关注

标签:Trapping,hStack,int,42,Rain,height,pStack,new,Stack
来源: https://blog.csdn.net/AXIMI/article/details/104521477