实现思路:典型对撞指针题型,设置两个指针一个在最左边,一个最右边,然后当左边指针小于右边指针的情况下,首先设置一个记录最大面积的变量area,计算area=max(min(a[i],a[j])*(r-l),area)不断更新值最后得出答案
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Two Pointers
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int maxArea(vector<int>& height) {
assert(height.size() >= 2);
int l = 0, r = height.size() - 1;
int area = 0;
while(l < r){
area = max(area , min(height[l], height[r]) * (r - l));
if(height[l] < height[r])
l ++;
else
r --;
}
return area;
}
};
int main() {
vector<int> nums1 = {1, 1};
cout << Solution().maxArea(nums1) << endl;
return 0;
}