题目链接




Python3
class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
n = len(heights)
res = [0] * n
stack = []
for i in range(n - 1, -1, -1):
while stack and heights[i] > stack[-1]:
res[i] += 1
stack.pop()
if stack:
res[i] += 1
stack.append(heights[i])
return res

C++
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
int n = heights.size();
vector<int> res(n, 0);
vector<int> stk;
for (int i = n - 1; i >= 0; --i){
while (!stk.empty() && heights[i] > stk.back()){
res[i] += 1;
stk.pop_back();
}
if (!stk.empty()){
res[i] += 1;
}
stk.emplace_back(heights[i]);
}
return res;
}
};
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
int n = heights.size();
vector<int> res(n, 0);
stack<int> stk;
for (int i = n - 1; i >= 0; --i){
while (!stk.empty() && heights[i] > stk.top()){
res[i] += 1;
stk.pop();
}
if (!stk.empty()){
res[i] += 1;
}
stk.push(heights[i]);
}
return res;
}
};