[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
lines are drawn such that the two endpoints of line i is
at
forms a container, such that the container contains the most water.
Example
Given
area of the container is
使用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;
}
}
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算法题解
- LintCode Majority Number iii
- LintCode-最大数
- lintCode Intersection of Two Arrays II
- Intersection of Two Arrays
- Subtree
- LintCode
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- lintcode之不同子序列数 + 序列II
- lintcode之快速幂
- lintcode删除排序数组中的重复数字 II
- lintcode之数组划分
- leetcode之三数之和 II
- lintcode之 数组剔除元素后的乘积
- lintcode之 合并排序数组 II
- lintcode 之子数组之和