Leetcode84.柱状图中最大的矩形
文章链接:代码随想录
文章链接:84.柱状图中最大的矩形
思路:暴力双指针,超时
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int result = 0;
for (int i = 0; i < heights.size(); i++){
int l = i;
int r = i;
for (; l >= 0; l--){
if (heights[l] < heights[i]) break;
}
for (; r < heights.size(); r++){
if (heights[r] < heights[i]) break;
}
int w = r - l - 1;
int h = heights[i];
result = max(result, w * h);
}
return result;
}
};
优化1(自己优化),依然超时,本质上还是没优化,时间复杂度一样
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int result = 0;
vector<int> nexl(heights.size(), -1);
vector<int> nexr(heights.size(), heights.size());
for (int i = 0; i < heights.size(); i++){
for (int j = i - 1; j >= 0; j--){
if (heights[j] < heights[i]){
nexl[i] = j;
break;
}
}
}
for (int i = heights.size() - 1; i >= 0; i--){
for (int j = i + 1; j < heights.size(); j++){
if (heights[j] < heights[i]){
nexr[i] = j;
break;
}
}
}
for (int i = 0; i < heights.size(); i++){
int w = nexr[i] - nexl[i] - 1;
int h = heights[i];
result = max(result, w * h);
}
return result;
}
};
优化了双指针,在优化过程中用上了之前记录的nexl、nexr中的信息,降低了时间复杂度
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int result = 0;
vector<int> nexl(heights.size(), -1);
vector<int> nexr(heights.size(), heights.size());
for (int i = 0; i < heights.size(); i++){
int j = i - 1;
while (j >= 0 && heights[j] >= heights[i]) j = nexl[j];
nexl[i] = j;
}
for (int i = heights.size() - 1; i >= 0; i--){
int j = i + 1;
while (j < heights.size() && heights[j] >= heights[i]) j = nexr[j];
nexr[i] = j;
}
for (int i = 0; i < heights.size(); i++){
int w = nexr[i] - nexl[i] - 1;
int h = heights[i];
result = max(result, w * h);
}
return result;
}
};
单调栈,和接雨水正好相反,是找元素两边第一个比本身小的,数组前后需要各插入一个0,避免递增或递减序列无法正确计算
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int result = 0;
heights.insert(heights.begin(), 0);
heights.push_back(0);
//heights.insert(heights.end(), 0);
stack<int> st;
st.push(0);
for (int i = 1; i < heights.size(); i++){
if (heights[i] > heights[st.top()]) st.push(i);
else if (heights[i] == heights[st.top()]) {
st.pop();
st.push(i);
}
else{
while(!st.empty() && heights[i] < heights[st.top()]){
int mid = st.top();
st.pop();
if (!st.empty()){
int w = i - st.top() - 1;
int h = heights[mid];
result = max(result, h * w);
}
}
st.push(i);
}
}
return result;
}
};
第六十天打卡,撒花完结;
未来的路还很长,不管结果与否,既然选定了目标,就要坚持坚持坚持,起码不会辜负自己,加油!!!