[LeetCode] Number of Visible People in a Queue

1944. Number of Visible People in a Queue

There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.

A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], …, heights[j-1]).

Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
int n = heights.size();
vector<set<int>> higher(n, set<int>());
vector<int> res(n, 0);
for(int i = n -2; i >= 0; i--) {
if(heights[i] <= heights[i + 1]) higher[i].insert(i + 1);
else {
set<int> s{i + 1};
queue<int> q;
q.push(i + 1);
while(!q.empty()) {
auto pos = q.front();
q.pop();
if(heights[i] > heights[pos]) {
res[i]++;
for(auto& higher : higher[pos]) {
if(!s.count(higher)) {
q.push(higher);
s.insert(higher);
}
}
} else {
higher[i].insert(pos);
}
}
}
res[i] += higher[i].size();
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
int n = heights.size();
vector<int> res(n, 0), st;
for(int i = 0; i < n; i++) {
while(!st.empty() and heights[st.back()] <= heights[i]) {
res[st.back()]++;
st.pop_back();
}
if(!st.empty()) res[st.back()]++;
st.push_back(i);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/24/PS/LeetCode/number-of-visible-people-in-a-queue/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.