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 (i,ai) 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 ContainerWithMostWater {
     2     public static int maxArea(int[] height){
     3         int maxarea = 0;
     4         int area = 0;
     5         int l = 0;
     6         int r = height.length - 1;
     7         while( l < r){
     8             area = min(height[l] , height[r]) * ( r - l);
     9             if ( area > maxarea)
    10                 maxarea = area;
    11             
    12             if( height[l] < height[r])
    13                 l++;
    14             else
    15                 r--;
    16         }
    17         return maxarea;
    18     }
    19     
    20     static int min( int a,int b){
    21         return a>b ? b : a;
    22     }
    23 }
  • 相关阅读:
    第六章
    第七章
    第五章
    第四章
    第三章
    第二章
    第一章
    Android深度探索——第十章读书笔记及心得
    Android深度探索——第九章读书笔记及心得
    Android深度探索——第八章读书笔记及心得
  • 原文地址:https://www.cnblogs.com/myshuangwaiwai/p/4683479.html
Copyright © 2011-2022 走看看