s0503
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Sainnhe Park 2022-12-16 16:12:04 +08:00
parent 676611e233
commit 1775c33c9f
4 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,14 @@
#ifndef S0503_NEXT_GREATER_ELEMENT_II_HPP
#define S0503_NEXT_GREATER_ELEMENT_II_HPP
#include <vector>
#include <stack>
using namespace std;
class S0503 {
public:
vector<int> nextGreaterElements(vector<int>& nums);
};
#endif

View File

@ -29,6 +29,16 @@
[496. 下一个更大元素 I](https://leetcode.com/problems/next-greater-element-i/) [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] ...
}
```
## 队列 ## 队列
使用场景: 使用场景:

View File

@ -0,0 +1,36 @@
#include "s0503_next_greater_element_ii.hpp"
// 循环数组首先考虑到的方法就是将两个数组拼接到一起处理。
// 我们将两个数组拼接到一起,然后用单调栈即可,但这样做有些浪费内存。
// 另一种处理方式是这样遍历:
// for (int i{0}; i < 2 * len; ++i) {
// nums[i % len] ...
// }
vector<int> S0503::nextGreaterElements(vector<int>& nums) {
int len = nums.size();
if (len == 0) {
return vector<int> {};
} else if (len == 1) {
return vector<int> {-1};
}
vector<int> ans(len, -1);
stack<int> 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;
}

View File

@ -0,0 +1,17 @@
#include "s0503_next_greater_element_ii.hpp"
#include <gtest/gtest.h>
TEST(Problem503, Case1) {
vector<int> nums{1, 2, 1};
vector<int> expected{2, -1, 2};
S0503 solution;
EXPECT_EQ(solution.nextGreaterElements(nums), expected);
}
TEST(Problem503, Case2) {
vector<int> nums{1, 2, 3, 4, 3};
vector<int> expected{2, 3, 4, -1, 4};
S0503 solution;
EXPECT_EQ(solution.nextGreaterElements(nums), expected);
}