Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

解法:

  最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,将较短的边向中间移,因为我们想看看能不能把较短的边换长一点。这样一直计算到指针重合为止就行了。

public class Solution {
public int maxArea(int[] height) {
int max = 0;
int i = 0;
int j = height.length - 1;
while (i < j) {
int lower = Math.min(height[i], height[j]);
max = Math.max(lower * (j - i), max);
if (height[i] < height[j]) i++;
else j--;
}
return max;
}
}

  改进:如果较短的边向中间移动后,新的边比原来的短,可以直接跳过,找下一条边,减少一些计算量。

public class Solution {
public int maxArea(int[] height) {
int max = 0;
int i = 0;
int j = height.length - 1;
while (i < j) {
int lower = Math.min(height[i], height[j]);
max = Math.max(lower * (j - i), max);
if (height[i] < height[j])
while (i < j && height[i] <= lower) i++;
else
while (i < j && height[j] <= lower) j--;
}
return max;
}
}

最新文章

  1. C/C++内存泄露探测
  2. C# FTP 命令无法获取ServerU目录列表问题
  3. React Native组件之Text
  4. 【BZOJ】【1034】【ZJOI2008】泡泡堂BNB
  5. C/S打包(图文)
  6. css3图片墙
  7. Java 常调用的Webservice接口的方法
  8. 纯js实现div内图片自适应大小
  9. imx6平台qt锯齿原因分析
  10. Java变量和对象的作用域
  11. itextpdf添加非自带字体(例如微软雅黑)
  12. Spring MVC 知识点记忆
  13. 【HNOI 2016】序列
  14. 【leetcode】485. Max Consecutive Ones
  15. 【uoj207】 共价大爷游长沙
  16. python内置函数,lambda表达式,文件读写
  17. 玩vue+mockjs
  18. (转)Java程序员应该知道的10个调试技巧
  19. 完美解决onchange不能实时的监听
  20. HUD 1175 连连看

热门文章

  1. QT打开文件路径中含有中文和空格问题
  2. 3.hadoop完全分布式搭建
  3. 官方文档 恢复备份指南一 Introduction to Backup and Recovery
  4. [leetcode-663-Equal Tree Partition]
  5. 自测之Lesson14:多线程编程
  6. 第一周—Fortran语言学习
  7. Alpha-2
  8. name(实例化类名).hbm.xml文件案例
  9. Android------去除标题栏
  10. Swift &amp; Unicode