LeetCode――Container With Most Water

2015-07-24 05:39:14 · 作者: · 浏览: 8

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.

给定n个非负整数a1,a2,……,an,每个代表坐标(i,ai)上的一个点,n条直线的两端分别是(i,ai) ,(i,0)。找出两条直线,使其与x轴形成一个容器,使容器包含最多的水。

注意:你不可以倾斜容器。

原题比较直白的解释大概如此:数组中的每个元素代表一个水槽的边,找出两条边,使得水槽的体积最大。

这里不用考虑宽度,只要 底 x 高 最大即可。即两个水槽边的距离要越远,边的高度要越大,但是根据“木桶原理”,此处由高度较小的边决定。

即可由两边向中间搜索,找到使得面积最大的两条边。

	public int maxArea(int[] height) {
		int area = 0;
		int i = 0, j = height.length - 1;
		while (i < j) {
			area = Math.max(area, (j - i) * Math.min(height[i], height[j]));
			if (height[i] > height[j])
				j--;
			else
				i++;
		}
		return area;
	}