链接:LintCode 炼码 - ChatGPT!更高效的学习体验!
题解:
1.从左往右维护一个单调递减,栈的长度就是,可以看到最多的高楼
2.从右往后也是维护一个单调递减的栈
class Solution {
public:
/**
* @param arr: the height of all buildings
* @return: how many buildings can he see at the location of each building
*/
vector<int> tallBuilding(vector<int> &arr) {
// Write your code here.
if (arr.size() <= 0) {
return arr;
}
std::vector<int> result(arr.size(), 1);
calc(arr, result, 0, arr.size(), 1);
calc(arr, result, arr.size()-1, -1, -1);
return result;
}
private:
void calc(const std::vector<int>& arr, std::vector<int>& result, int begin, int end, int step) {
std::stack<int> sta;
for (int i = begin; i != end; i += step) {
result[i] += sta.size();
while (!sta.empty() && arr[sta.top()] <= arr[i]) {
sta.pop();
}
sta.push(i);
}
}
};