#84 Largest Rectangle in Histogram

Description

Given an array of integers heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Examples

Example 1:
在这里插入图片描述

Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.

Example 2:
在这里插入图片描述

Input: heights = [2,4]
Output: 4

Constraints:

1 <= heights.length <= 105
0 <= heights[i] <= 104

Solution

一开始我以为要用动态规划,但规划了半天都没规划出来,还是用简单的 O ( n 2 ) O(n^2) O(n2)方法吧

对每个位置都计算以该高度为长方形的高,能拓展出去的最大面积

有一个需要注意的点

  • 当height[i] ==height[i - 1]的时候,是不用重复计算的,否则会Time Limited Exceeded

还有一个可以改进的点,和字符串匹配的kwp算法比较接近,预存一个position[]数组,position[i]表示height[i]对应的长方形最左侧位置。(代码2)

代码1

class Solution {
    public int largestRectangleArea(int[] heights) {
        int answer = 0;
        int i, j;
        for(i = 0; i < heights.length; i++){
            if(i > 0 && heights[i] == heights[i - 1])
                continue;   // key point
            int temp = heights[i];
            for(j = i; j >= 0; j--){
                if (heights[i] > heights[j])
                    break;
            }
            temp = temp + (i - j - 1) * heights[i];
            for(j = i; j < heights.length; j++){
                if (heights[i] > heights[j])
                    break;
            }
            temp = temp + (j - i - 1) * heights[i];
            if(answer < temp)
                answer = temp;
        }
        return answer;
    }
}

代码2

class Solution {
    public int largestRectangleArea(int[] heights) {
        int answer = 0;
        int[] position = new int[heights.length];
        int i, j;
        for(i = 0; i < heights.length; i++){
            if(i > 0 && heights[i] == heights[i - 1]){
                position[i] = position[i - 1];
                continue;   // key point
            }
            int temp = heights[i];
            for(j = i - 1; j >= 0; j--){
                if (heights[i] > heights[j])
                    break;
                else
                    j = position[j] + 1;
            }
            position[i] = j;
            temp = temp + (i - j - 1) * heights[i];
            for(j = i + 1; j < heights.length; j++){
                if (heights[i] > heights[j])
                    break;
            }
            temp = temp + (j - i - 1) * heights[i];
            if(answer < temp)
                answer = temp;
        }
        return answer;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值