题解 | #直方图内最大矩形 单调栈#

直方图内最大矩形

http://www.nowcoder.com/practice/bfaac4eebe5947af80912d1bcfcf2baa

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param heights int整型一维数组 
     * @return int整型
     */
    public int largestRectangleArea (int[] heights) {
        if (heights.length == 0){
            return 0;
        }
        if (heights.length == 1) {
            return heights[0];
        }
        int ans = 0;
        LinkedList<Integer> list = new LinkedList<>();
        list.add(0);
        for (int i = 1; i < heights.length; i++) {
            if (heights[list.peekLast()] <= heights[i]) {
                list.addLast(i);
            } else {
                while (!list.isEmpty() && heights[list.peekLast()] > heights[i]) {
                    int temp = list.pollLast();
                    if (list.isEmpty()) {
                        ans = Math.max(ans, heights[temp] * (i - (-1) - 1));
                    } else {
                        ans = Math.max(ans, heights[temp] * (i - list.peekLast() - 1));
                    }
                }
                list.add(i);
            }
        }
        while (!list.isEmpty()) {
            int temp = list.pollLast();
            while (!list.isEmpty() && heights[temp] == heights[list.peekLast()]){
                temp = list.pollLast();
            }
            if (list.isEmpty()) {
                ans = Math.max(ans, heights[temp] * (heights.length - (-1) - 1));
            } else {
                ans = Math.max(ans, heights[temp] * (heights.length - list.peekLast() - 1));
            }
        }
        return ans;
    }
}
全部评论

相关推荐

smile丶snow:项目完成时间要写一个大概的区间,自己顺延一下就行。感觉ai对话的放第一个比较好。可以自己编一些场景或者找ai编一个场景。就是你为什么要写这个仿DeepSeek对话应用。比如你自己有很多文档,这个ai可以基于你自己的文档回答之类的。个人建议~具体看你自己。 还有项目中用到那些更好让ai coding的方法也可以写一下,毕竟现在ai大跃进…
简历被挂麻了,求建议
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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