diff --git a/README.md b/README.md index 4cebd79..1dbf36d 100644 --- a/README.md +++ b/README.md @@ -417,6 +417,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文 ### 栈 +- [队列中可以看到的人数](src/stack/number_of_visible_people_in_a_queue.cpp) [栈, 数组, 单调栈] + + - LeetCode 1944. 队列中可以看到的人数 + - [从链表中移除节点](src/stack/remove_nodes_from_linked_list.cpp) [栈, 递归, 链表, 单调栈] - LeetCode 2487. 从链表中移除节点 diff --git a/images/stack/number_of_visible_people_in_a_queue.jpeg b/images/stack/number_of_visible_people_in_a_queue.jpeg new file mode 100644 index 0000000..ced441e Binary files /dev/null and b/images/stack/number_of_visible_people_in_a_queue.jpeg differ diff --git a/src/stack/number_of_visible_people_in_a_queue.cpp b/src/stack/number_of_visible_people_in_a_queue.cpp new file mode 100644 index 0000000..298055f --- /dev/null +++ b/src/stack/number_of_visible_people_in_a_queue.cpp @@ -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 + +class Solution { +public: + vector canSeePersonsCount(vector &heights) { + int n = heights.size(); + vector res(n, 0); + vector 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; + } +}; \ No newline at end of file diff --git a/test/lib/lib_test.cpp b/test/lib/lib_test.cpp index e07b7d4..babfe53 100644 --- a/test/lib/lib_test.cpp +++ b/test/lib/lib_test.cpp @@ -1,4 +1,4 @@ -// 执行编译时间:2024-01-04 09:37:38 +// 执行编译时间:2024-01-05 14:42:19 #include #include diff --git a/test/stack/number_of_visible_people_in_a_queue_test.cpp b/test/stack/number_of_visible_people_in_a_queue_test.cpp new file mode 100644 index 0000000..47d537d --- /dev/null +++ b/test/stack/number_of_visible_people_in_a_queue_test.cpp @@ -0,0 +1,25 @@ +#include + +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); +}