题解 | 接雨水问题

接雨水问题

https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * max water
     * @param arr int整型一维数组 the array
     * @return long长整型
     */
    public long maxWater (int[] arr) {
        // write code here
        LinkedList<Data> stack = new LinkedList<Data>();
        int count =0;
        for (int i = 0; i < arr.length; i++) {
            Data data = new Data(arr[i],i);
            while (!stack.isEmpty() && data.height >  stack.peek().height) {
             Data pop= stack.pop();
             Data left=stack.peek();
             if( left!=null ){
               int width = data.i-left.i-1;
               int height = Math.min(left.height,data.height)-pop.height;
               count += width*height;
              }
            }
            stack.push(data);
        }
        return count;
    }

    static class Data{
        int height;
        int  i;
        public Data(int height,int i){
           this.height =height;
           this.i =i;
        }
    }
}

用单调栈解决,注意细节,不要用一个top指针指向栈顶元素再去比较,不然就一直比较的这个元素,即使是这个元素弹出了这个栈;

全部评论

相关推荐

27双非本,最近面试被挂麻了面试官说简历内容太简单了,技术栈要单独一行,各位佬有啥建议吗
LZStarV:项目太简单了,你像用什么开发的技术栈没必要写一句话,按点写就好了;有特色的比如说WebSocket、视频流这种狠狠吹,那就好看多了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务