原题:
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 linei 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.
给定一个数组,用其表示二维坐标系(coordinate)的点。数组元素下标对应坐标系横坐标,元素值对应纵坐标。坐标系上两个点与横轴的垂线段和横轴组成“桶”,找到能装最多水的桶。
有点像短板效应,每个桶装满水时水的体积是底(两点横坐标之差)x 高(纵坐标最小的点的纵坐标)。
思考过程:
个人浅见,写算法实在模拟人类思维。见到这个题,除了o(n^2)复杂度的算法,没有更好的算法。看了答案,惊叹作答案者思维的巧妙,总之我是没有想到。
解题思路:
挨个遍历的算法不多赘述。
答案时间复杂度是o(n),答案思路是:先用最两侧两条边形成“桶”;如果这个桶想变大,而且是在底不能变大的情况下,只能是让短边变长。因此从短边一侧,向中间遍历,找出比最短边长的一条边取代最短边形成新桶。将此过程所有桶的容积计算,每次将最大值存到int型变量res里,遍历结束res就是结果。
一开始觉得这个思路很巧妙但不太相信它的准确性,后来思考了一下:想找最大桶,如果一条边确定了,另一条边没有理由选离它又近又没它高的。所以只有比它高才有可能有新的突破。
结果代码:
public int maxArea(int[] height) { int left = 0,right = height.length - 1,res = 0;//left,righ分别为所假设最大桶的两边 while (left < right) { res = Math.max(res, (Math.min(height[left], height[right]) * (right - left))); if (height[left] < height[right]) left++; else right--; } return res; }