class Solution {
//Find two lines, which together with x-axis forms a container, such that the container contains the most water.
//if do not together with x-axis forms a container,
//and together with other lines then it will be more difficult to find out an effective solution
public:
int maxArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int l = 0;
int r = height.size()-1;
int ans = 0;
while (l < r)
{
int tmp = min(height[r], height[l])*(r-l);
if(tmp > ans) ans = tmp;
if(height[r] < height[l])
r--;
else l++;
}
return ans;
}
};
second time
class Solution {
//greedy based solution
public:
int maxArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int left = 0, right = height.size()-1;
int maxArea = 0;
while(left < right)
{
maxArea = max(maxArea, min(height[left], height[right])*(right-left));
if(height[left] < height[right]) left++;
else right--;
}
return maxArea;
}
};
本文介绍了一种寻找能盛最多水的两条线的有效算法。通过双指针技术从两端逐步向中间逼近,每次更新最大面积并调整较短的边,最终找到最优解。
383

被折叠的 条评论
为什么被折叠?



