Leetcode 084 Largest Rectangle in Histogram(高效)

题目连接:Leetcode 084 Largest Rectangle in Histogram

解题思路:基本思路是维护每个位置向左向右最远不小于自己的位置l[i],r[i]。在处理l[i]时,只需要从左向右遍历一遍heights数组,遍历过程中维护一个递增的t数组和它们对应的位置p,每次删除t数组中比heights[i]低的数,那么t中剩下的元素最后一个即为当前位置向左第一个小于自己的位置,更新l[i]值,然后交给heights[i]也放入t数组,用于求解后面的位置。r数组同理。因为每个元素只会进入t和移除t一次,所以复杂度为o(n)。

class Solution {
	public:
		int largestRectangleArea(vector<int>& heights) {
			int n = heights.size();
			int* l = new int[n];
			int* r = new int[n];

			int* t = new int[n+1];
			int* p = new int[n+1];

			t[0] = -1, p[0] = -1;
			int c = 1;
			for (int i = 0; i < n; i++) {
				while (c > 0 && t[c-1] >= heights[i]) c--;
				l[i] = p[c-1] + 1;
				t[c] = heights[i];
				p[c++] = i;
			}

			p[0] = n, c = 1;
			for (int i = n-1; i >= 0; i--) {
				while (c > 0 && t[c-1] >= heights[i]) c--;
				r[i] = p[c-1] - 1;
				t[c] = heights[i];
				p[c++] = i;
			}

			int ans = 0;
			for (int i = 0; i < n; i++)
				ans = max(ans, (r[i] - l[i] + 1) * heights[i]);

			delete[] l;
			delete[] r;
			delete[] t;
			delete[] p;

			return ans;
		}
};

猜你喜欢

转载自blog.csdn.net/u011328934/article/details/80714472