This commit is contained in:
parent
676611e233
commit
1775c33c9f
14
include/s0503_next_greater_element_ii.hpp
Normal file
14
include/s0503_next_greater_element_ii.hpp
Normal 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
|
@ -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] ...
|
||||
}
|
||||
```
|
||||
|
||||
## 队列
|
||||
|
||||
使用场景:
|
||||
|
36
src/s0503_next_greater_element_ii.cpp
Normal file
36
src/s0503_next_greater_element_ii.cpp
Normal 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;
|
||||
}
|
17
tests/s0503_next_greater_element_ii.cpp
Normal file
17
tests/s0503_next_greater_element_ii.cpp
Normal 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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user