zoukankan      html  css  js  c++  java
  • 【leetcode】11. Container With Most Water

    题目描述:

    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.

    解题思路:

    先找距离最长的两个位置看能装下多少水,随后缩小两边的距离,因为距离减少,所以要先使得所能容纳的水变多,只能提高形成的“桶”的高度。因为高度与最低的边界一致,所以缩小边界时要从值小的那一边找,知道找到大于“桶高”的值,说明桶的高度可以得到提升,计算新桶所能容纳的体积并与最大值比较。以此类推,知道两边不能在缩小位置。

    具体代码:

     1 public class Solution {
     2    public static int maxArea(int[] height) {
     3         if(height==null||height.length<=0)
     4             return 0;
     5         if(height.length==2){
     6             int n=Math.min(height[0], height[1]);
     7             return n;
     8         }
     9         
    10         
    11         int from=0;
    12         int to=height.length-1;
    13         int min=Math.min(height[from], height[to]);
    14         int max=(to-from)*min;
    15         while(from<to){
    16             if(height[from]<=height[to]){
    17                 from++;
    18                 while(from<to && height[from]<=min){
    19                     from++;
    20                 }
    21             }
    22             else{
    23                 to--;
    24                 while(from<to && height[to]<=min){
    25                     to--;
    26                 }
    27             }
    28             min=Math.min(height[from], height[to]);
    29             int area=(to-from)*min;
    30             if(max<area)
    31                 max=area;
    32         }
    33         return max;
    34     }
    35 }
  • 相关阅读:
    ||和&&
    用jQuery编的一个分页小代码
    Intent携带额外的数据的方法
    Handler消息传递机制
    安卓中的消息提示
    使用AlertDialog创建对话框的大致步骤
    布局管理器
    Android中支持的常用距离单位
    开发自定义View
    Gridview中奇偶数行颜色设置
  • 原文地址:https://www.cnblogs.com/godlei/p/5582607.html
Copyright © 2011-2022 走看看