LeetCode 11
Container With Most Water
Problem Description:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.Solution 1:
这个解法是最容易想到的==但也是显然超时的,不过通过此解法可以确定自己对题目的理解是正确的,继续往下改善
class Solution {
public:
int maxArea(vector<int>& height) {
int max_water = 0;
for (int i = 0; i < height.size()-1; i++) {
for (int j = i+1; j < height.size(); j++) {
int temp = height[i]<height[j]? height[i]:height[j];
if (temp*(j-i) > max_water)
max_water = temp*(j-i);
}
}
return max_water;
}
};
- Solution2:
主要思路:用两个变量left和right标记从数组两边遍历的位置,先计算出当前位置两条line和底边长度(right-left)围成的的面积,然后对其中一条line进行移进操作(判断条件:哪个变量对应的函数值小,就对该line移进使之靠近中心),再次计算围成的面积,比较后取max即可。
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size()-1;
int max_water = 0;
while (left < right) {
int min_water = height[left]<height[right]? height[left]:height[right];
int temp = min_water*(right-left);
if (temp > max_water)
max_water = temp;
if (height[left]<height[right]) {
left++;
} else {
right--;
}
}
return max_water;
}
};