Skip to content

Commit

Permalink
leetcode: Add cpp impl to 0496
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Sep 21, 2024
1 parent 7d4ef61 commit aade7cb
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/leetcode/0496.next-greater-element-i/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/main
3 changes: 3 additions & 0 deletions src/leetcode/0496.next-greater-element-i/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

build: main.cpp
g++ -g main.cpp -o main
6 changes: 6 additions & 0 deletions src/leetcode/0496.next-greater-element-i/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,10 @@
```rust
{{#include src/main.rs:5:6}}
{{#include src/main.rs:40:70}}
```

C++ 实现如下:

```cpp
{{#include main.cpp:5:}}
```
77 changes: 77 additions & 0 deletions src/leetcode/0496.next-greater-element-i/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

#include <cassert>
#include <climits>

#include <iostream>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>

std::vector<int> nextGreaterElement(std::vector<int>& nums1, std::vector<int>& nums2) {
std::stack<int> monotonic_stack;
std::unordered_map<int, int> map;
int max_num = INT_MAX;

// 构造递增式单调栈
for (int num2 : nums2) {
if (num2 < max_num) {
// 将较小的元素入栈
max_num = num2;
monotonic_stack.push(num2);
} else {
// 将较小的元素出栈
while (!monotonic_stack.empty() && monotonic_stack.top() < num2) {
const int top = monotonic_stack.top();
monotonic_stack.pop();
map.emplace(top, num2);
}
// 将当前元素入栈
monotonic_stack.push(num2);
}
}

std::vector<int> out;
for (int num1 : nums1) {
auto iter = map.find(num1);
if (iter == map.cend()) {
out.push_back(-1);
} else {
out.push_back(iter->second);
}
}

return out;
}

void checkSolution() {
{
std::vector<int> nums1 = {4, 1, 2};
std::vector<int> nums2 = {1, 3, 4, 2};
std::vector<int> expected = {-1, 3, -1};
assert(nextGreaterElement(nums1, nums2) == expected);
}

{
std::vector<int> nums1 = {2, 4};
std::vector<int> nums2 = {1, 2, 3, 4};
std::vector<int> expected = {3, -1};
assert(nextGreaterElement(nums1, nums2) == expected);
}

{
std::vector<int> nums1 = {1, 3, 5, 2, 4};
std::vector<int> nums2 = {6, 5, 4, 3, 2, 1, 7};
std::vector<int> expected = {7, 7, 7, 7, 7};
assert(nextGreaterElement(nums1, nums2) == expected);
}
}

int main() {
checkSolution();

return 0;
}

0 comments on commit aade7cb

Please sign in to comment.