11. Container With Most Water

62次阅读

共计 964 个字符,预计需要花费 3 分钟才能阅读完成。

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 and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:Input: [1,8,6,2,5,4,8,3,7]Output: 49
难度:medium
题目:给定 n 个非负整数 a1, a2, … an, 每个点表示坐标上的点。n 条垂直线连接两点 (i, ai) 和 (i, 0)。找出两条线和X轴形成的容器所能盛的最多水。
注意:容器不能倾斜,n 至少为 2.
思路:从最左到最右向中间夹挤。向中间的移动的条件为哪边高度小哪边向中间移动。
Runtime: 4 ms, faster than 99.64% of Java online submissions for Container With Most Water.
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length – 1;
int maxArea = 0, width = 0, minHeight = height[0];
for (; left < right;) {
width = right – left;
minHeight = height[left] > height[right] ? height[right–] : height[left++];
maxArea = Math.max(maxArea, width * minHeight);
}

return maxArea;
}
}

正文完
 0