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));  }}