Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that thetwo endpoints of line i isat (i, ai) and (i,0). Find two lines, which together with x-axis forms a container, such that thecontainer contains the most water.
Note: You may not slant the container and n is at least 2.
分析:
其实就是找到最大的面积数。i就相当于坐标的X,Y就是高,面积就是X乘以Y。
在本题中,a[i] , a[j]表示yi和yj ,Y = min(yi,yj)。取桶最矮的一部分。
j – i =X(j > i)桶底部的宽度。
面积就是X * Y = min(yi,yj) * j – i;
考虑到a的长度大小为n,不难看出最优的时间复杂度为O(n)
int maxArea(vector<int>& height) { int max = 0; int start = 0; int end = height.size() - 1; int temp = 0; max = min(height[0],height[end]) * (end - start); for( ; start < end ; start++){ while(height[start] > height[end] && start < end){ temp = min(height[start],height[end]) * (end - start); if(max < temp) max = temp; end--; } temp = min(height[start],height[end]) * (end - start); if(max < temp) max = temp; } return max; }
)。
因此,可以从两边向中间遍历数组(个人比较喜欢两边向中间遍历,其他方法也可以),稍微利用一点对桶高的贪心思维。每次保留最长的Y,然后从另外一边遍历。比如
2 1 3 4 5 2 1 4
start表示开始的下标,end表示结束的下标
现在看到a[start]是2,a[end]是4,4 > 2 ,从左边遍历,start++。
然后一直走到5,5 > 4 ,然后从右边开始走,end--,到start不小于end就结束了。每次走到一个点的时候就计算面积的值,然后和历史最大面积比较,取较大值保存,算法结束后就得到最大面积的值。
最后,算法复杂度就是O(n)。