41. First Missing Positive
来源:互联网 发布:nginx 代理iis 编辑:程序博客网 时间:2024/06/05 17:12
41. First Missing Positive
题目描述:Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogra
题目大意:给定n个正整数代表的高度,每个bar的宽度为1,求能构成最大矩形的面积。
思路:使用栈的目的就是构造这样的升序序列,按照以上方法求解。
但是height本身不一定是升序的,应该怎样构建栈?
比如2,1,5,6,2,3
(1)2进栈。s={2}, result = 0
(2)1比2小,不满足升序条件,因此将2弹出,并记录当前结果为2*1=2。
将2替换为1重新进栈。s={1,1}, result = 2
(3)5比1大,满足升序条件,进栈。s={1,1,5},result = 2
(4)6比5大,满足升序条件,进栈。s={1,1,5,6},result = 2
(5)2比6小,不满足升序条件,因此将6弹出,并记录当前结果为6*1=6。s={1,1,5},result = 6
2比5小,不满足升序条件,因此将5弹出,并记录当前结果为5*2=10(因为已经弹出的5,6是升序的)。s= {1,1},result = 10
2比1大,将弹出的5,6替换为2重新进栈。s={1,1,2,2,2},result = 10
(6)3比2大,满足升序条件,进栈。s={1,1,2,2,2,3},result = 10
栈构建完成,满足升序条件,因此按照升序处理办法得到上述的max(height[i]*(size-i))=max{3*1, 2*2, 2*3, 2*4, 1*5, 1*6}=8<10
综上所述,result=10
代码:
package Array;import java.util.Stack;/*** @Author OovEver* @Date 2017/11/30 21:50*/public class LeetCode84 { public static int largestRectangleArea(int[] height) { int res = 0; Stack<Integer> stack = new Stack<>(); for(int i=0;i<height.length;i++) { if (stack.empty() || stack.peek() < height[i]) { stack.push(height[i]); } else { int count = 0; while (!stack.empty() && stack.peek() > height[i]) { count++; res = Math.max(res, stack.pop() * count); } while (count-->0) { stack.push(height[i]); } stack.push(height[i]); } } int count = 1; while (!stack.isEmpty()) { res = Math.max(res, stack.pop() * count); count++; } return res; } public static void main(String[] args) { int[] nums = {1, 2, 3, 4, 5}; System.out.println(largestRectangleArea(nums)); }}
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 41. First Missing Positive
- 数据缺失的中文字符串
- 【数据平台】pandas按条件去重
- 通过先序和中序数组生成后序数组
- MBG(Mybatis generator)自动生成sql语句
- spring通过注解配置Bean
- 41. First Missing Positive
- java单例模式
- POCO线程池分析
- 未来保险MediShares你能想象到的场景都能为你实现
- Git常用命令
- spring boot 1.5.4 集成shiro+cas,实现单点登录和权限控制
- vs工程项目修改继承的值
- 基础练习 矩阵乘法
- 更改 Windows VM 的可用性集