From 1775c33c9fcd5e0498948479072cbbe82843ade2 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 16 Dec 2022 16:12:04 +0800 Subject: [PATCH] s0503 --- include/s0503_next_greater_element_ii.hpp | 14 +++++++++ notes/src/stack_and_queue.md | 10 +++++++ src/s0503_next_greater_element_ii.cpp | 36 +++++++++++++++++++++++ tests/s0503_next_greater_element_ii.cpp | 17 +++++++++++ 4 files changed, 77 insertions(+) create mode 100644 include/s0503_next_greater_element_ii.hpp create mode 100644 src/s0503_next_greater_element_ii.cpp create mode 100644 tests/s0503_next_greater_element_ii.cpp diff --git a/include/s0503_next_greater_element_ii.hpp b/include/s0503_next_greater_element_ii.hpp new file mode 100644 index 0000000..b079f8d --- /dev/null +++ b/include/s0503_next_greater_element_ii.hpp @@ -0,0 +1,14 @@ +#ifndef S0503_NEXT_GREATER_ELEMENT_II_HPP +#define S0503_NEXT_GREATER_ELEMENT_II_HPP + +#include +#include + +using namespace std; + +class S0503 { + public: + vector nextGreaterElements(vector& nums); +}; + +#endif diff --git a/notes/src/stack_and_queue.md b/notes/src/stack_and_queue.md index 4517090..d565317 100644 --- a/notes/src/stack_and_queue.md +++ b/notes/src/stack_and_queue.md @@ -29,6 +29,16 @@ [496. 下一个更大元素 I](https://leetcode.com/problems/next-greater-element-i/) +[503. 下一个更大元素 II](https://leetcode.com/problems/next-greater-element-ii/) + +Tips: 循环数组的处理方法: + +```cpp +for (int i{0}; i < 2 * len; ++i) { + nums[i % len] ... +} +``` + ## 队列 使用场景: diff --git a/src/s0503_next_greater_element_ii.cpp b/src/s0503_next_greater_element_ii.cpp new file mode 100644 index 0000000..9afa0c7 --- /dev/null +++ b/src/s0503_next_greater_element_ii.cpp @@ -0,0 +1,36 @@ +#include "s0503_next_greater_element_ii.hpp" + +// 循环数组首先考虑到的方法就是将两个数组拼接到一起处理。 +// 我们将两个数组拼接到一起,然后用单调栈即可,但这样做有些浪费内存。 +// 另一种处理方式是这样遍历: +// for (int i{0}; i < 2 * len; ++i) { +// nums[i % len] ... +// } + +vector S0503::nextGreaterElements(vector& nums) { + int len = nums.size(); + if (len == 0) { + return vector {}; + } else if (len == 1) { + return vector {-1}; + } + vector ans(len, -1); + stack s; + for (int i{0}; i < 2 * len; ++i) { + if (s.empty()) { + s.push(i); + continue; + } + while (nums[i % len] > nums[s.top() % len]) { + if (ans[s.top() % len] == -1) { + ans[s.top() % len] = nums[i % len]; + } + s.pop(); + if (s.empty()) { + break; + } + } + s.push(i); + } + return ans; +} diff --git a/tests/s0503_next_greater_element_ii.cpp b/tests/s0503_next_greater_element_ii.cpp new file mode 100644 index 0000000..25b83ec --- /dev/null +++ b/tests/s0503_next_greater_element_ii.cpp @@ -0,0 +1,17 @@ +#include "s0503_next_greater_element_ii.hpp" + +#include + +TEST(Problem503, Case1) { + vector nums{1, 2, 1}; + vector expected{2, -1, 2}; + S0503 solution; + EXPECT_EQ(solution.nextGreaterElements(nums), expected); +} + +TEST(Problem503, Case2) { + vector nums{1, 2, 3, 4, 3}; + vector expected{2, 3, 4, -1, 4}; + S0503 solution; + EXPECT_EQ(solution.nextGreaterElements(nums), expected); +}