LeetCode 84 Largest Rectangle in Histogram
2016-06-13 17:32
351 查看
问题
https://leetcode.com/problems/largest-rectangle-in-histogram/解法1
枚举法, 时间复杂度O(n^2)// TLE class Solution { public: int largestRectangleArea(vector<int>& heights) { int ret = 0; for (int i=0; i< heights.size(); ++i) { int L, R; for (L =i; L >=0 && heights[L] >= heights[i]; --L); ++L; for (R = i; R <heights.size() && heights[R] >= heights[i]; ++R); --R; ret = max(ret, (R+1-L) * heights[i]); } return ret; } };
解法2
使用堆栈优化, 时间复杂度N, 空间复杂度N首先注意到, 包含位置i的最大结果一段是段头的前一个位置(start range)和段尾后一个位置(end ranger)为都比位置i小(或者是数组边界),比如[2,1,5,6,2,3, 1], 包含位置i = 4 则最大结果是 【5, 6, 2, 3】 ,段头的前一个位置1, 段尾后一个位置1都比2 小。我们枚举数组中的每一个位置K, 之前位置中比当前位置K 数大的位置最多扩展到当前位置K, 即当前位置K为这些位置的end range,如果我们使用堆栈记录所有没有求得最大值的位置, 则枚举到每个位置时, 栈中元素是按照升序排列, 此时栈中前一个位置,即为start range。
每次出栈时计算一次长度, 所有元素只会有一次出栈, 因此时间复杂度为N,需要有一个堆栈空间复杂度为N
class Solution { public: int largestRectangleArea(vector<int>& heights) { stack<int> s; heights.push_back(-1); int ret =0; for (int i=0; i<heights.size(); ++i) { while(s.size() && heights[i] < heights[s.top()]) { int h = heights[s.top()]; s.pop(); int start = s.empty() ? -1:s.top(); ret = max(ret, h*(i - start -1)); } s.push(i); } return ret; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解