This commit is contained in:
parent
914c04c9c5
commit
090003819d
13
include/s0011_container_with_most_water.hpp
Normal file
13
include/s0011_container_with_most_water.hpp
Normal file
@ -0,0 +1,13 @@
|
||||
#ifndef S0011_CONTAINER_WITH_MOST_WATER
|
||||
#define S0011_CONTAINER_WITH_MOST_WATER
|
||||
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int maxArea(vector<int>& height);
|
||||
};
|
||||
|
||||
#endif
|
24
src/s0011_container_with_most_water.cpp
Normal file
24
src/s0011_container_with_most_water.cpp
Normal file
@ -0,0 +1,24 @@
|
||||
#include "s0011_container_with_most_water.hpp"
|
||||
|
||||
// 双指针:
|
||||
// 一开始左指针指向数组开头,右指针指向数组结尾
|
||||
// 两个指针向中间移动
|
||||
// 每次移动的时候移动较小的那个指针:
|
||||
// 由于储存的水量 = 两指针之间的距离 * 较小的指针的值
|
||||
// 因此如果移动较大的指针,那么储存的水量一定不会超过之前的
|
||||
// 也就是说只有当移动小的指针时才有可能让储存的水量超过之前的
|
||||
// 因此每次迭代我们移动较小的指针,然后统计出最大的储存水量
|
||||
|
||||
int Solution::maxArea(vector<int>& height) {
|
||||
int max{0};
|
||||
for (int l{0}, r{static_cast<int>(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;
|
||||
}
|
17
tests/s0011_container_with_most_water.cpp
Normal file
17
tests/s0011_container_with_most_water.cpp
Normal file
@ -0,0 +1,17 @@
|
||||
#include "s0011_container_with_most_water.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(Problem11, Case1) {
|
||||
vector<int> 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<int> height{1, 1};
|
||||
int o{1};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.maxArea(height), o);
|
||||
}
|
Loading…
Reference in New Issue
Block a user