Skip to content

Commit

Permalink
add: 队列中可以看到的人数
Browse files Browse the repository at this point in the history
  • Loading branch information
yi-ge committed Jan 5, 2024
1 parent 5241b54 commit 6b6f3ef
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文

###

- [队列中可以看到的人数](src/stack/number_of_visible_people_in_a_queue.cpp) [栈, 数组, 单调栈]

- LeetCode 1944. 队列中可以看到的人数 <https://leetcode.cn/problems/number-of-visible-people-in-a-queue>

- [从链表中移除节点](src/stack/remove_nodes_from_linked_list.cpp) [栈, 递归, 链表, 单调栈]

- LeetCode 2487. 从链表中移除节点 <https://leetcode.cn/problems/remove-nodes-from-linked-list>
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions src/stack/number_of_visible_people_in_a_queue.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// 队列中可以看到的人数
// https://leetcode.cn/problems/number-of-visible-people-in-a-queue
// INLINE ../../images/stack/number_of_visible_people_in_a_queue.jpeg

#include <headers.hpp>

class Solution {
public:
vector<int> canSeePersonsCount(vector<int> &heights) {
int n = heights.size();
vector<int> res(n, 0);
vector<int> stack;

for (int i = n - 1; i >= 0; i--) {
int h = heights[i];
while (!stack.empty() && stack.back() < h) {
stack.pop_back();
res[i] += 1;
}
if (!stack.empty()) {
res[i] += 1;
}
stack.push_back(h);
}
return res;
}
};
2 changes: 1 addition & 1 deletion test/lib/lib_test.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// 执行编译时间:2024-01-04 09:37:38
// 执行编译时间:2024-01-05 14:42:19
#include <gtest/gtest.h>
#include <lib.hpp>

Expand Down
25 changes: 25 additions & 0 deletions test/stack/number_of_visible_people_in_a_queue_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <stack/number_of_visible_people_in_a_queue.cpp>

TEST(队列中可以看到的人数, canSeePersonsCount) {
Solution solution;
// 示例 1:
// 输入:heights = [10,6,8,5,11,9]
// 输出:[3,1,2,1,1,0]
// 解释:
// 第 0 个人能看到编号为 1 ,2 和 4 的人。
// 第 1 个人能看到编号为 2 的人。
// 第 2 个人能看到编号为 3 和 4 的人。
// 第 3 个人能看到编号为 4 的人。
// 第 4 个人能看到编号为 5 的人。
// 第 5 个人谁也看不到因为他右边没人。
vector heights = {10, 6, 8, 5, 11, 9};
vector result = {3, 1, 2, 1, 1, 0};
EXPECT_EQ(solution.canSeePersonsCount(heights), result);

// 示例 2:
// 输入:heights = [5,1,2,3,10]
// 输出:[4,1,1,1,0]
vector heights2 = {5, 1, 2, 3, 10};
vector result2 = {4, 1, 1, 1, 0};
EXPECT_EQ(solution.canSeePersonsCount(heights2), result2);
}

0 comments on commit 6b6f3ef

Please sign in to comment.