盛最多水的容器(双指针法)

This commit is contained in:
carry 2025-02-13 22:00:59 +08:00
parent 16b0c2ae64
commit 8dc2f5e9a5

View File

@ -9,18 +9,21 @@ public:
int maxArea(vector<int> &height) int maxArea(vector<int> &height)
{ {
int maxArea = 0; int maxArea = 0;
for(int i = 0; i < height.size(); i++) int left = 0;
{ int right = height.size() - 1;
for(int j = i + 1; j < height.size(); j++) while (left < right){
{ maxArea = max(maxArea,(right - left)*min(height[right] , height[left]));
int area = min(height[i], height[j]) * (j - i); if( height[left] < height[right]){
maxArea = max(maxArea, area); left++;
}
else{
right--;
} }
} }
return maxArea; return maxArea;
} }
}; };
int main() int main()
{ {
vector<int> height = {1, 8, 6, 2, 5, 4, 8, 3, 7}; vector<int> height = {1, 8, 6, 2, 5, 4, 8, 3, 7};