zoukankan      html  css  js  c++  java
  • LeetCode: Largest Rectangle in Histogram

    没想出来,看了网上答案再改了改

     1 class Solution {
     2 public:
     3     struct node {
     4         int left;
     5         int right;
     6     };
     7     int largestRectangleArea(vector<int> &height) {
     8         // Start typing your C/C++ solution below
     9         // DO NOT write int main() function
    10         int n = height.size();
    11         vector<struct node> record(n);
    12         for (int i = 0; i < n; i++) {
    13             record[i].left = i;
    14             while (record[i].left > 0 && height[i] <= height[record[i].left-1])
    15                 record[i].left = record[record[i].left-1].left;            
    16         }
    17         for (int i = n-1; i >= 0; i--) {
    18             record[i].right = i;
    19             while (record[i].right < n-1 && height[i] <= height[record[i].right+1])
    20                 record[i].right = record[record[i].right+1].right;
    21         }
    22         int largest = 0;
    23         for (int i = 0; i < n; i++)
    24             largest = max(largest, height[i] * (record[i].right - record[i].left + 1));
    25         return largest;
    26     }
    27 };

     再贴段容易理解的代码

     1 class Solution {
     2 public:
     3     int largestRectangleArea(vector<int> &h) {
     4         stack<int> S;
     5         h.push_back(0);
     6         int sum = 0;
     7         for (int i = 0; i < h.size(); i++) {
     8             if (S.empty() || h[i] > h[S.top()]) S.push(i);
     9             else {
    10                 int tmp = S.top();
    11                 S.pop();
    12                 sum = max(sum, h[tmp]*(S.empty()? i : i-S.top()-1));
    13                 i--;
    14             }
    15         }
    16         return sum;
    17     }
    18 };

     C#

     1 public class Solution {
     2     public int LargestRectangleArea(int[] height) {
     3         Stack<int> S = new Stack<int>();
     4         int[] heights = new int[height.Length+1];
     5         int sum = 0;
     6         Array.Copy(height, heights, height.Length);
     7         for (int i = 0; i < heights.Length; i++) {
     8             if (S.Count == 0 || heights[i] > heights[S.Peek()]) S.Push(i);
     9             else {
    10                 int peek = S.Peek();
    11                 S.Pop();
    12                 sum = Math.Max(sum, heights[peek]*(S.Count == 0? i : i-S.Peek()-1));
    13                 i--;
    14             }
    15         }
    16         return sum;
    17     }
    18 }
    View Code
  • 相关阅读:
    排查oom方法
    逃逸分析-栈上分配
    java堆是分配对象的唯一选择吗
    GC
    jvm为什么把-Xms和-Xmx的值设置成一样
    java堆
    java为何使用native 方法
    linux top命令信息详解
    java定位系统性能问题
    struts 初体验
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/2994655.html
Copyright © 2011-2022 走看看