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

[Lintcode]Container With Most Water

2016-09-04 15:59 337 查看
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.

Example

Given 
[1,3,2]
, the max
area of the container is 
2
.

使用O(N×N)算法会超时。另外一种O(N)算法的思想是,每次放弃ai,aj中最小的,因为假如ai较小,那么以ai为左边界遍历的所有结果不会超过当前的容量。所以放弃ai, i++。如此一来避免了不必要的计算。

public class Solution {
/**
* @param heights: an array of integers
* @return: an integer
*/
public int maxArea(int[] heights) {
int left = 0, right = heights.length - 1;
int res = 0;
while(left < right) {
int tmp = heights[left] > heights[right] ? heights[right] : heights[left];
res = Math.max(res, tmp * (right - left));
if(heights[left] > heights[right]) right --;
else left ++;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode