LeetCode题库解答与分析——#11.盛最多水的容器ContainerWithMostWater

#11 盛最多水的容器 Container With Most Water

给定 n 个正整数 a1a2,...,an,其中每个点的坐标用(iai)表示。 画 n 条直线,使得线 i 的两个端点处于(i,ai)和(i,0)处。请找出其中的两条直线,使得他们与 X 轴形成的容器能够装最多的水。

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.

注意:你不能倾斜容器,n 至少是2。

他人思路:

从两边向中间,比较两线高度,每次都舍弃最短的并向中心移动一位,同时根据两边距离和最短边高度得到面积。由于最短边是每个长方形面积的决定因素,因而每次只挪动短边的一端,直到两端相遇。

代码(JavaScript):

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    var left = 0, right = height.length - 1;
	var maxArea = 0;

	while (left < right) {
		maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));
		if (height[left] < height[right])
			left++;
		else
			right--;
	}

	return maxArea;
};

你可能感兴趣的:(LeetCode)