您的位置:首页 > 大数据 > 人工智能

[Leetcode]Container With Most Water

2015-10-16 17:33 204 查看
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.

题意:给定一系列和x轴垂直相交的线,线的起点坐标和终点坐标分别为(i, ai)和
(i,
0),找出其中的两条线满足Min(ai, aj)
* |j - i|最大(j和i代表垂直线的x轴值,j和i作为角标,谁大谁小都可以,这里假定j > i)。

解法一:时间复杂度为O(N^2),双重循环解法本文不做讨论;

解法二:时间复杂度为O(N)

public class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;

int maxArea = 0;
int currentArea = 0;
while (left < right) {
currentArea = (right - left) * (height[left] < height[right] ? height[left] : height[right]);

if (currentArea > maxArea) {
maxArea = currentArea;
}

if (height[left] <= height[right]) {
++left;
} else {
--right;
}
}
return maxArea;
}
}


对于两条线:(i, Ai),(j, Aj),i < j,它们所形成的容器的面积为:
area(i, j) = (j - i) * min{Ai, Aj}
当Ai < Aj时,对于以(i, Ai)为一条垂直边的所有容器,若在[i, j]直接有另外一条线[k, Ak],[i, Ai]和[k, Ak]形成的容器面积为
area(i, k) = (k - i) * min{Ai, Ak},
显然 k -i < j -i,所以:
(k
- i) * min{Ai, Ak} < (j - i) * min{Ai, Ak},
而(k
- i) * min{Ai, Ak} <= (k - i) * Ai < (j - i) * Ai < (j- i) * min{Ai, Aj},

即(k - i) * min{Ai, Ak} < (j-
i) * min{Ai, Aj},

结论:在[i, j],且Ai < Aj,在以[i, Ai]为一条边的所有水容器中,[i, Ai]和[j, Ak]所形成的水容器面积最大。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: