zoukankan      html  css  js  c++  java
  • Leetcode 11. Container With Most Water(逼近法)

    11. Container With Most Water
    Medium

    Given n non-negative integers a1, a2, ..., a, 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 and n is at least 2.

    The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

    Example:

    Input: [1,8,6,2,5,4,8,3,7]
    Output: 49

    这个题想了很久,结果没想到怎么做,其实现在理解以下就是一个双边贪心的策略,尽量的宽,又尽力的高才能存储更多的水,所以,从两端向中间贪心,如果左边的比右边的高就更新右边的边,往中间靠一阶,看能不能得到更好的,同理,如果右边的比左边的短,右边就向右扫描一个,如果相等,那随便选择一边更新一格就可以。
     1 class Solution {
     2 public:
     3     int maxArea(vector<int>& height) {
     4         int r = 0; int l = height.size()-1;
     5         int Max = (min(height[l],height[r])*(l-r)); 
     6         while(r<l){
     7             if(height[r] <= height[l]) r++;
     8             else if(height[l] < height[r]) l--;
     9             Max = max(Max,(min(height[l],height[r])*(l-r)));  
    10         }
    11         return Max;
    12     }
    13 };
  • 相关阅读:
    JSP_core
    J2EE_Servlet——helloworld
    JS_对象原型链
    JDBC_Hive & coding
    Python错误——TypeError: 'NoneType' object is not iterable
    Python错误——TypeError: is_leap_year() takes 0 positional arguments but 1 was given
    python错误:sh: cls: command not found
    Git——版本控制系统
    samba服务器搭建+权限设置
    windows10 samba 安全策略无法访问
  • 原文地址:https://www.cnblogs.com/shanyr/p/11434814.html
Copyright © 2011-2022 走看看