From 83266bbc5b533a1608539537b87ce06a75299c79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=B5=D0=B2=20=D0=90=D0=BB=D0=B5=D0=BA?= =?UTF-8?q?=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= Date: Sat, 30 Sep 2023 13:53:24 +0300 Subject: [PATCH] 132 Pattern --- CMakeLists.txt | 1 + solutions/132-pattern/CMakeLists.txt | 1 + solutions/132-pattern/solution.hpp | 28 ++++++++++++++++++++++++++++ solutions/132-pattern/test.cpp | 22 ++++++++++++++++++++++ 4 files changed, 52 insertions(+) create mode 100644 solutions/132-pattern/CMakeLists.txt create mode 100644 solutions/132-pattern/solution.hpp create mode 100644 solutions/132-pattern/test.cpp 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)); + } +}