模式识别:双指针法
这种需要动两头的都可以用双指针法,这题的思路是,只移动短边,因为如果移动长边,还是以短边为妥协的,每次只移动短边,不会错过正确答案。
#include<iostream>
#include<vector>
using namespace std;
//笨方法,超出时间限制了
class Solution1 {
public:
int maxArea(vector<int>& height) {
int max = 0;
for (int i = 0; i < height.size(); i++){
for (int j = i + 1; j < height.size(); j++) {
int water = (j - i) * min(height[i], height[j]);
if (water > max) {
max = water;
}
}
}
return max;
}
};
//模式识别:需要移动左右两头的都可以考虑双指针
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size() - 1;
int max = (right - left) * min(height[left], height[right]);
while ((right - left) != 1) {
if (height[left] < height[right]) {
left++;
}
else{
right--;
}
int water = (right - left) * min(height[left], height[right]);
if (water > max) {
max = water;
}
}
return max;
}
};
int main() {
Solution test;
vector<int>height = { 1,2,1 };
cout << test.maxArea(height);
}