leetcode-11- container with most water

题目

给定一个数组,数组的下标代指二维横坐标,数组值代指纵坐标,选取两点,找出组成矩形面积最大值(即,所组成的桶装水的最大值)

分析

利用首尾指针,left,right
height[left] < height[right]那么left++,否则right–

C++代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int (vector<int>& height) {
int capability = 0;
int left = 0;
int right = height.size()-1;
while(left<right){
int s = min(height[right],height[left]) * (right-left);
if(s>capability)
capability = s;
if(height[left]<height[right])
left++;
else right--;
}
return capability;
}
};