这题其实是一道很典型的单调栈的题目:
我很早就想到了,但是无奈写了很久没写出来,还是不够熟练...
所以单调栈是用来解决什么问题的呢?顾名思义,他帮我们维护一个单调的序列。在这里,我们在一个位置i,要向左看,也要向右看,我们能看到的楼,是高度单调递增的。
具体代码如下所示,是我在Clion中写的:
#include <bits/stdc++.h>
using namespace std;
vector<int> findBuilding(vector<int>& heights){
int len=heights.size();
stack<int> forward;
stack<int> back;
vector<int> left(len);
vector<int> right(len);
for (int i = 0; i < len; ++i) {
left[i]=forward.size();
while(!forward.empty()&&heights[i]>=forward.top()){
forward.pop();
}
forward.push(heights[i]);
}
for (int i = len-1; i >= 0; --i) {
right[i]=back.size();
while(!back.empty()&&heights[i]>=back.top()){
back.pop();
}
back.push(heights[i]);
}
vector<int> res;
for (int i = 0; i < len; ++i) {
res.push_back(left[i]+right[i]+1);
}
return res;
}
int main() {
vector<int> heights={5,3,8,3,2,5};
vector<int> res= findBuilding(heights);
for (int num:res) {
cout<<num<<" ";
}
return 0;
}
|