zoukankan      html  css  js  c++  java
  • 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.

    Note: You may not slant the container and n is at least 2.

    给定n个非负整数12,...,n,其中每个代表坐标(ii处的一个点绘制n条垂直线,使得线i的两个端点处于(ii)和(i,0)处。找到两条线,它们与x轴一起形成一个容器,使得容器包含最多的水。

    注意:你可能不倾斜容器,n至少为2。

    (1)思想1:定义 begin=0 和 end=height.size() 两个指针分别指向数组的左右两端,然后两个指针向中间搜索,每移动一次算一个值和结果比较取较大的,容器装水量的算法是找出左右两个边缘中较小的那个乘以两边缘的距离(即矩形的面积)。

    C++:

     1 class Solution {
     2 public:
     3     int maxArea(vector<int>& height) {
     4         int begin=0,end=height.size()-1;
     5         int res=0;
     6         while(begin<end)
     7         {
     8             res=max(res,min(height[begin],height[end])*(end-begin));
     9             if(height[begin]<height[end])
    10                 begin++;
    11             else
    12                 end--;
    13         }
    14         return res;
    15     }
    16 };
  • 相关阅读:
    Linux命令大全
    Restframework 视图组件与序列号组件的应用.
    Linux常用命令
    数据结构
    MongoDB
    算法
    Flask 语音分析
    Flask Session ,pymysql ,wtforms组件 虚拟virtualenv venv
    Flask 视图,模板,蓝图.
    Flask初识
  • 原文地址:https://www.cnblogs.com/sword-/p/8059792.html
Copyright © 2011-2022 走看看