LeetCode算法题目:Largest Rectangle in Histogram

来源:互联网 发布:网络电影《宝宝别哭》 编辑:程序博客网 时间:2024/06/16 00:00

题目:

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 histogram.

这里写图片描述

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

这里写图片描述
The largest rectangle is shown in the shaded area, which has area = 10 unit.

  • For example,
  • Given heights = [2,1,5,6,2,3],
    return 10.

    分析:

    如果在面试的过程中被问到这个题目,除非之前见过,否则一时很难想到解法。我们不妨从最笨的解法入手。在我看来,能把最笨的解法写出来也是很不错的,毕竟很多人见到这种题一下就蒙了。
    最笨的解法是什么呢,就是遍历所有的起始和结束位置,然后计算该区域内长方形的面积,找到最大的。具体实现过程中,从第0个位置开始遍历起点,选定起点之后,从起点到末尾都可以当做终点,所以总共有O(n2)种可能。在固定了起点之后,后续对终点的遍历有一个特点:构成长方形的高度都不高于之前所构造长方形的高度,所以长方形的高度即是到当前终点为止的最小值,宽度即是终点位置减去起点位置加1。

    代码:

    此代码复杂度为O(n^2),运行时会超时。

    class Solution {public:    int largestRectangleArea(vector<int>& heights) {        int len=heights.size();        int max_size=0;        for(int i=0;i<len;i++)        {            int min_height=heights[i];            int current_size=min_height;            for(int j=i;j<len;j++)            {                if(heights[j]<min_height) min_height=heights[j];                current_size=min_height*(j-i+1);                if(current_size>max_size) max_size=current_size;            }        }        return max_size;    }};

    下面给出网上的用栈实现的复杂度为O(n)的解法。没看懂,在此仅给出链接。
    http://chuansong.me/n/390896436960
    http://blog.csdn.net/yutianzuijin/article/details/52072427

    1 0
    原创粉丝点击