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.
解题思路:
本题是经典的“水箱”问题,最简单的方法是暴力枚举,时间复杂度是O(N^2),当然无法通过。
本题有三个特征:
一、水箱的高度是由最短那根木板决定的
二、最终符合条件的两根木板肯定比他们各自外围的木板长
三、最终符合条件的两个木板的外围高度要小于这两个木板中最短的那个,即最终符合条件的两个木板肯定是所有遍历过的最高的两个(比较拗口,但是是解决本题的关键)
因此我们可以从最外围木板出发,向内遍历,每次替换掉两个之中最短的木板,肯定能遍历到最大容器(目标木板)。
JAVA实现如下:
static public int maxArea(int[] height) { if (height.length < 2) return 0; int maxV = 0, start = 0, end = height.length - 1; while (start < end) { int area = Math.min(height[start], height[end]) * (end - start); maxV = Math.max(maxV, area); if (height[start] > height[end]) end--; else start++; } return maxV; }
C++:
1 #include<vector> 2 #include<algorithm> 3 using namespace std; 4 class Solution { 5 public: 6 int maxArea(vector<int>& height) { 7 if (height.size() < 2) 8 return 0; 9 int maxV = 0, start = 0, end = height.size() - 1; 10 while (start < end) { 11 maxV = max(maxV, min(height[start], height[end]) * (end - start)); 12 if (height[start] > height[end]) 13 end--; 14 else 15 start++; 16 } 17 return maxV; 18 } 19 };