From 090003819d95111b50d7f168402b9262e0526474 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Thu, 3 Nov 2022 15:22:56 +0800 Subject: [PATCH] s0011 --- include/s0011_container_with_most_water.hpp | 13 +++++++++++ src/s0011_container_with_most_water.cpp | 24 +++++++++++++++++++++ tests/s0011_container_with_most_water.cpp | 17 +++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 include/s0011_container_with_most_water.hpp create mode 100644 src/s0011_container_with_most_water.cpp create mode 100644 tests/s0011_container_with_most_water.cpp diff --git a/include/s0011_container_with_most_water.hpp b/include/s0011_container_with_most_water.hpp new file mode 100644 index 0000000..f8c8a47 --- /dev/null +++ b/include/s0011_container_with_most_water.hpp @@ -0,0 +1,13 @@ +#ifndef S0011_CONTAINER_WITH_MOST_WATER +#define S0011_CONTAINER_WITH_MOST_WATER + +#include + +using namespace std; + +class Solution { + public: + int maxArea(vector& height); +}; + +#endif diff --git a/src/s0011_container_with_most_water.cpp b/src/s0011_container_with_most_water.cpp new file mode 100644 index 0000000..1b0a353 --- /dev/null +++ b/src/s0011_container_with_most_water.cpp @@ -0,0 +1,24 @@ +#include "s0011_container_with_most_water.hpp" + +// 双指针: +// 一开始左指针指向数组开头,右指针指向数组结尾 +// 两个指针向中间移动 +// 每次移动的时候移动较小的那个指针: +// 由于储存的水量 = 两指针之间的距离 * 较小的指针的值 +// 因此如果移动较大的指针,那么储存的水量一定不会超过之前的 +// 也就是说只有当移动小的指针时才有可能让储存的水量超过之前的 +// 因此每次迭代我们移动较小的指针,然后统计出最大的储存水量 + +int Solution::maxArea(vector& height) { + int max{0}; + for (int l{0}, r{static_cast(height.size() - 1)}; r != l;) { + if (height.at(l) > height.at(r)) { + max = (r - l) * height.at(r) > max ? (r - l) * height.at(r) : max; + r--; + } else { + max = (r - l) * height.at(l) > max ? (r - l) * height.at(l) : max; + l++; + } + } + return max; +} diff --git a/tests/s0011_container_with_most_water.cpp b/tests/s0011_container_with_most_water.cpp new file mode 100644 index 0000000..7e86dda --- /dev/null +++ b/tests/s0011_container_with_most_water.cpp @@ -0,0 +1,17 @@ +#include "s0011_container_with_most_water.hpp" + +#include + +TEST(Problem11, Case1) { + vector height{1, 8, 6, 2, 5, 4, 8, 3, 7}; + int o{49}; + Solution solution; + EXPECT_EQ(solution.maxArea(height), o); +} + +TEST(Problem11, Case2) { + vector height{1, 1}; + int o{1}; + Solution solution; + EXPECT_EQ(solution.maxArea(height), o); +}