[leetcode]84. Largest Rectangle in Histogram c语言

来源:互联网 发布:手机域名价格 编辑:程序博客网 时间:2024/06/16 01: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.

思路
自己能想到就是O(n2)的解法(依次算每个高度能形成的最大面积),时间超过限制。学习了下其他人的解法http://blog.csdn.net/doc_sgl/article/details/11805519
从左依次遍历高度数组,高度有增加时,就把每个下标依次存在栈中,当有断崖出现时。就出栈并计算断崖前的最大面积。理解栈中始终存着一个阶梯状的高度下标。

int largestRectangleArea(int* heights, int heightsSize) {    int *stack = NULL, max = 0;    int *dupHeights = NULL;    int top = -1;    int area = 0;    int i;    if(!heights || !heightsSize)        return 0;    stack = (int *)malloc(heightsSize * sizeof(int));    if(!stack)        return 0;    dupHeights = (int *)malloc((heightsSize + 1) * sizeof(int));    if(!dupHeights)        return 0;    /* 末尾追加高度0,以便最后出栈所有下标 */    memcpy(dupHeights, heights, heightsSize * sizeof(int));    dupHeights[heightsSize] = 0;    for(i = 0; i < heightsSize + 1; )    {        if(top == -1 || dupHeights[i] >= dupHeights[stack[top]])        {            top++;            stack[top] = i;            i++;        }        else        {                 if(top == 0)            {                area = dupHeights[stack[top]] * i;                top--;            }            else            {                area = dupHeights[stack[top]] * (i - stack[top-1] - 1);                top--;            }            if(max < area)                max = area;        }    }    free(stack);    free(dupHeights);    return max;}

Run Time:8ms

0 0