[LeetCode]99. Container with Most Water最大容积
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.
Subscribe to see which companies asked this question
在第一象限存在点(1,a1),(2,a2),...,(n,an),这些点各自与(1,0),(2,0),...,(n,0)连成一条条垂直线,任取两条(i,ai)和(j,aj),与(i,j)组成一个容器,求能够得到的最大容积的(i,ai)和(j,aj)。
解法1:暴力破解,两层循环求出所有容器的容积,然后取最大值。Time Limit Exceeded
class Solution { public: int maxArea(vector<int>& height) { int n = height.size(), maxContain = 0; for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { int minHeight = min(height[i], height[j]); int contain = (j - i) * minHeight; if (contain > maxContain) maxContain = contain; } } return maxContain; } };
解法2:题目提示使用两个指针。两个指针指向数组两端,计算出容积并更新结果;然后比较左右直线的高度,将高度较小的那个移动一步;直到两个指针相遇。
class Solution { public: int maxArea(vector<int>& height) { int left = 0, right = height.size() - 1, maxContain = 0; while (left < right) { maxContain = max(min(height[left], height[right]) * (right - left), maxContain); if (height[left] < height[right]) ++left; else --right; } return maxContain; } };