Skip to content

Commit

Permalink
132 Pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Sep 30, 2023
1 parent 6bcc6d8 commit 83266bb
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ endfunction()
enable_testing()

add_task(01-matrix)
add_task(132-pattern)
add_task(3sum)
add_task(3sum-closest)
add_task(add-binary)
Expand Down
1 change: 1 addition & 0 deletions solutions/132-pattern/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_132_pattern test.cpp)
28 changes: 28 additions & 0 deletions solutions/132-pattern/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#pragma once

#include <climits>
#include <stack>
#include <vector>

class Solution {
public:
static bool find132pattern(const std::vector<int> &nums) {
int middle = INT_MIN;
std::stack<int> stack;

for (int i = nums.size() - 1; i >= 0; --i) {
if (nums[i] < middle) {
return true;
}

while (!stack.empty() && stack.top() < nums[i]) {
middle = stack.top();
stack.pop();
}

stack.push(nums[i]);
}

return false;
}
};
22 changes: 22 additions & 0 deletions solutions/132-pattern/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
{
std::vector<int> nums{1, 2, 3, 4};
REQUIRE_FALSE(Solution::find132pattern(nums));
}
{
std::vector<int> nums{3, 1, 4, 2};
REQUIRE(Solution::find132pattern(nums));
}
{
std::vector<int> nums{-1, 3, 2, 0};
REQUIRE(Solution::find132pattern(nums));
}
{
std::vector<int> nums{1, 0, 1, -4, -3};
REQUIRE_FALSE(Solution::find132pattern(nums));
}
}

0 comments on commit 83266bb

Please sign in to comment.