zoukankan      html  css  js  c++  java
  • Container With Most Water leetcode java

    题目:

    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.

    Note: You may not slant the container.

    题解:

     这道题挺类似二分查找法的,这道题是先从两头开始算面积,面积的计算要由短板决定,并维护一个当前最大面积。

     然后逐步替换小的短板来计算面积。每一步只替换短板的原因是,短板决定面积,而高板不影响,所以要想有所改变就改变那个有决定性的东西。。

     网上有好多人都画出图来了。。可以搜搜看。。。

     代码如下:

     1     public int maxArea(int[] height) {
     2         if(height == null || height.length == 0)
     3             return 0;
     4         
     5         int low = 0, high = height.length -1 ;  
     6         int max = 0;  
     7         while (low < high) {
     8          int area = (high-low)*Math.min(height[low], height[high]);
     9          
    10          max = Math.max(max, area);  
    11          if (height[low] < height[high])  
    12              low++;  
    13          else  
    14              high--;  
    15         }  
    16             return max;  
    17     }

  • 相关阅读:
    visual studio 注释
    EF Core导航属性
    【转】前端UI框架小汇总
    C#三种定时器的实现
    【转】自学MVC看这里——全网最全ASP.NET MVC 教程汇总
    【转】C#进阶系列——WebApi 接口参数不再困惑:传参详解
    【转】c# WebApi之解决跨域问题:Cors
    优秀.NET开源项目
    Linux简介及最常用命令
    C#中使用Socket实现简单Web服务器
  • 原文地址:https://www.cnblogs.com/springfor/p/3871017.html
Copyright © 2011-2022 走看看