# polebug/LeetCode

Fetching contributors…
Cannot retrieve contributors at this time
40 lines (31 sloc) 1.63 KB
 /* Descriprion: 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. Example 1: Input: [1,8,6,2,5,4,8,3,7] Output: 49 Hints: 感觉这题非常 leetcode 的了。属于那种，可以很水(数据太弱)，但也可以不水的题目。 我把这题归为区间类型的题目，气氛上就是找到某个满足条件的区间即可。 暴力 O(n2) 我试过了，数据太弱了也是随便过。显然这个区间在移动的时候有一些特殊的地方，这里说一个 O(n) 的思路，其实也很简单，首先我们设定头尾两个指针。发现，如果这个区间的头指针所在的高度比尾指针的大，显然我们希望尾指针向前移动；那么如果头指针所在的高度比尾指针的小，显然头指针应该向后走。 */ class Solution { public: int maxArea(vector& height) { int maxn = 0, contain = 0; int left = 0, right = height.size() - 1; while (left < right) { int h; if(height[left]>height[right]) h = height[right]; else h = height[left]; contain = h * (right - left); if (contain > maxn) { maxn = contain; } if (height[left] < height[right]) left++; else right--; } return maxn; } };