LeetCode: Largest Rectangle in Histogram

没想出来,看了网上答案再改了改

 1 class Solution {

 2 public:

 3     struct node {

 4         int left;

 5         int right;

 6     };

 7     int largestRectangleArea(vector<int> &height) {

 8         // Start typing your C/C++ solution below

 9         // DO NOT write int main() function

10         int n = height.size();

11         vector<struct node> record(n);

12         for (int i = 0; i < n; i++) {

13             record[i].left = i;

14             while (record[i].left > 0 && height[i] <= height[record[i].left-1])

15                 record[i].left = record[record[i].left-1].left;            

16         }

17         for (int i = n-1; i >= 0; i--) {

18             record[i].right = i;

19             while (record[i].right < n-1 && height[i] <= height[record[i].right+1])

20                 record[i].right = record[record[i].right+1].right;

21         }

22         int largest = 0;

23         for (int i = 0; i < n; i++)

24             largest = max(largest, height[i] * (record[i].right - record[i].left + 1));

25         return largest;

26     }

27 };

 再贴段容易理解的代码

 1 class Solution {

 2 public:

 3     int largestRectangleArea(vector<int> &h) {

 4         stack<int> S;

 5         h.push_back(0);

 6         int sum = 0;

 7         for (int i = 0; i < h.size(); i++) {

 8             if (S.empty() || h[i] > h[S.top()]) S.push(i);

 9             else {

10                 int tmp = S.top();

11                 S.pop();

12                 sum = max(sum, h[tmp]*(S.empty()? i : i-S.top()-1));

13                 i--;

14             }

15         }

16         return sum;

17     }

18 };

 C#

 1 public class Solution {

 2     public int LargestRectangleArea(int[] height) {

 3         Stack<int> S = new Stack<int>();

 4         int[] heights = new int[height.Length+1];

 5         int sum = 0;

 6         Array.Copy(height, heights, height.Length);

 7         for (int i = 0; i < heights.Length; i++) {

 8             if (S.Count == 0 || heights[i] > heights[S.Peek()]) S.Push(i);

 9             else {

10                 int peek = S.Peek();

11                 S.Pop();

12                 sum = Math.Max(sum, heights[peek]*(S.Count == 0? i : i-S.Peek()-1));

13                 i--;

14             }

15         }

16         return sum;

17     }

18 }
View Code

 

你可能感兴趣的:(LeetCode)