leetcode——84. 柱状图中最大的矩形

class Solution(object):
    def largestRectangleArea(self, heights):
        """
        :type heights: List[int]
        :rtype: int
        """
        stack = []
        heights = [0] + heights + [0]
        res = 0
        for i in range(len(heights)):
            #print(stack)
            while stack and heights[stack[-1]] > heights[i]:
                tmp = stack.pop()
                res = max(res, (i - stack[-1] - 1) * heights[tmp])
            stack.append(i)
        return res
执行用时 :108 ms, 在所有 python 提交中击败了69.00%的用户
内存消耗 :13.6 MB, 在所有 python 提交中击败了41.18%的用户
 
这道题不太会。。。。
 
——2019.11.4
 

方法一:暴力法
public int largestRectangleArea(int[] heights) {
        //暴力法
        int area = 0;
        for(int i = 0;i<heights.length;i++){ //从i向两边遍历,找到所有连续的比i位置高度高的位置,即可得到中间长度
            int j = i;
            while(j-1>=0){
                if(heights[j-1] >= heights[i]){
                    j--;
                }else{
                    break;
                }
            }
            int k = i;
            while (k+1<heights.length){
                if(heights[k+1] >= heights[i]){
                    k++;
                }else{
                    break;
                }
            }
            area = Math.max((k-j+1)*heights[i],area);
        }
        return area;
    }

 

 方法二:栈

添加哨兵,单调栈

public int largestRectangleArea(int[] heights) {
        int len = heights.length;
        if (len == 0) {
            return 0;
        }

        if (len == 1) {
            return heights[0];
        }

        int res = 0;

        int[] newHeights = new int[len + 2];
        newHeights[0] = 0;
        System.arraycopy(heights, 0, newHeights, 1, len);
        newHeights[len + 1] = 0;
        len += 2;
        heights = newHeights;

        Deque<Integer> stack = new ArrayDeque<>(len);
        // 先放入哨兵,在循环里就不用做非空判断
        stack.addLast(0);

        for (int i = 1; i < len; i++) {
            while (heights[i] < heights[stack.peekLast()]) {
                int curHeight = heights[stack.pollLast()];
                int curWidth = i - stack.peekLast() - 1;
                res = Math.max(res, curHeight * curWidth);
            }
            stack.addLast(i);
        }
        return res;
    }

 

 ——2020.7.14

 

posted @ 2019-11-04 11:23  欣姐姐  阅读(247)  评论(0编辑  收藏  举报