diff --git a/CMakeLists.txt b/CMakeLists.txt index 333fb1be..219c62da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/solutions/132-pattern/CMakeLists.txt b/solutions/132-pattern/CMakeLists.txt new file mode 100644 index 00000000..3d9f6b6a --- /dev/null +++ b/solutions/132-pattern/CMakeLists.txt @@ -0,0 +1 @@ +add_catch(test_132_pattern test.cpp) diff --git a/solutions/132-pattern/solution.hpp b/solutions/132-pattern/solution.hpp new file mode 100644 index 00000000..50ca5d0e --- /dev/null +++ b/solutions/132-pattern/solution.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include + +class Solution { +public: + static bool find132pattern(const std::vector &nums) { + int middle = INT_MIN; + std::stack 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; + } +}; diff --git a/solutions/132-pattern/test.cpp b/solutions/132-pattern/test.cpp new file mode 100644 index 00000000..b1bb2fcb --- /dev/null +++ b/solutions/132-pattern/test.cpp @@ -0,0 +1,22 @@ +#include + +#include + +TEST_CASE("Simple") { + { + std::vector nums{1, 2, 3, 4}; + REQUIRE_FALSE(Solution::find132pattern(nums)); + } + { + std::vector nums{3, 1, 4, 2}; + REQUIRE(Solution::find132pattern(nums)); + } + { + std::vector nums{-1, 3, 2, 0}; + REQUIRE(Solution::find132pattern(nums)); + } + { + std::vector nums{1, 0, 1, -4, -3}; + REQUIRE_FALSE(Solution::find132pattern(nums)); + } +}