Monotonic queue

--

A 4th question of Biweekly LeetCode contest.

1944. Number of Visible People in a Queue

We can use a monotonic queue to solve this problem.

class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
const int n = heights.size();
vector<int> ret(n);
vector<int> q;
for (int i = n - 1; i >=0; --i){
while (!q.empty() && heights[i] > q.back()){
ret[i]++;
q.pop_back();
}
if (!q.empty())ret[i]++;
q.push_back(heights[i]);
}
return ret;
}
};

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet