Skip to content

Commit

Permalink
feat: 下一个更大元素IV
Browse files Browse the repository at this point in the history
  • Loading branch information
yi-ge committed Dec 12, 2023
1 parent 30a087c commit 2bc1da2
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文

### 排序

- [下一个更大元素 IV](src/sort/next_greater_element_iv.cpp) [栈, 数组, 二分查找, 排序, 单调栈, 堆(优先队列)]

- LeetCode 2454. 下一个更大元素 IV <https://leetcode.cn/problems/next-greater-element-iv>

- [出租车的最大盈利](src/sort/maximum_earnings_from_taxi.cpp) [数组, 二分查找, 动态规划, 排序]

- LeetCode 2008. 出租车的最大盈利 <https://leetcode.cn/problems/maximum-earnings-from-taxi>
Expand Down
Binary file added images/sort/next_greater_element_iv.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
30 changes: 30 additions & 0 deletions src/sort/next_greater_element_iv.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// 下一个更大元素 IV
// https://leetcode.cn/problems/next-greater-element-iv
// INLINE ../../images/sort/next_greater_element_iv.jpeg

#include <headers.hpp>

class Solution {
public:
vector<int> secondGreaterElement(vector<int> &nums) {
int n = nums.size();
vector<int> res(n, -1);
vector<int> st1;
vector<int> st2;
for (int i = 0; i < n; ++i) {
int v = nums[i];
while (!st2.empty() && nums[st2.back()] < v) {
res[st2.back()] = v;
st2.pop_back();
}
int pos = st1.size() - 1;
while (pos >= 0 && nums[st1[pos]] < v) {
--pos;
}
st2.insert(st2.end(), st1.begin() + (pos + 1), st1.end());
st1.resize(pos + 1);
st1.push_back(i);
}
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 @@
// 执行编译时间:2023-12-11 10:45:43
// 执行编译时间:2023-12-12 17:54:52
#include <gtest/gtest.h>
#include <lib.hpp>

Expand Down
26 changes: 26 additions & 0 deletions test/sort/next_greater_element_iv_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <sort/next_greater_element_iv.cpp>

TEST(下一个更大元素IV, secondGreaterElement) {
Solution solution;
// 示例 1:
// 输入:nums = [2,4,0,9,6]
// 输出:[9,6,6,-1,-1]
// 解释:
// 下标为 0 处:2 的右边,4 是大于 2 的第一个整数,9 是第二个大于 2 的整数。
// 下标为 1 处:4 的右边,9 是大于 4 的第一个整数,6 是第二个大于 4 的整数。
// 下标为 2 处:0 的右边,9 是大于 0 的第一个整数,6 是第二个大于 0 的整数。
// 下标为 3 处:右边不存在大于 9 的整数,所以第二大整数为 -1 。
// 下标为 4 处:右边不存在大于 6 的整数,所以第二大整数为 -1 。
// 所以我们返回 [9,6,6,-1,-1] 。
vector<int> nums = {2, 4, 0, 9, 6};
EXPECT_EQ(solution.secondGreaterElement(nums),
vector<int>({9, 6, 6, -1, -1}));

// 示例 2:
// 输入:nums = [3,3]
// 输出:[-1,-1]
// 解释:
// 由于每个数右边都没有更大的数,所以我们返回 [-1,-1] 。
nums = {3, 3};
EXPECT_EQ(solution.secondGreaterElement(nums), vector<int>({-1, -1}));
}

0 comments on commit 2bc1da2

Please sign in to comment.