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

    题目:
    LeetCode:11. Container With Most Water

    描述:

    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 and n is at least 2.
    
    1. 从已有的数组中,选找两个线段使得他能构成最大的盛水容器。
    2. 盛水容器,根据生活常识,容量取决于最短的那条边;
    3. 盛水容量为:S = a(长) * b(宽) = min(i , j) * (j - i ); // i,j 为当前选择的线段索引值;

    分析:

    1.暴力枚举

     // 思路;
    1、最暴力的方式就像遍历这个数组,计算任意两个组合的线段组成的面积大小,不可取;
    2、利用左右两边逼夹的方式,向中间运动,记录此时的面积,取最大值。
    3、移动时选择较小的边进行移动,并更新记录的两条线段索引。
    

    代码:

    int maxArea(vector<int>& height) {
        int nMax = 0;
        int nLeft = 0;
        int nRight = height.size() - 1;
        for (; nLeft < nRight;)
        {
            nMax = max(nMax, min(height[nLeft], height[nRight]) * (nRight - nLeft));
            if (height[nLeft] > height[nRight])
            {
                --nRight;
            }
            else
            {
                ++nLeft;
            }
        }
        return nMax;
    }
    

    备注:
    可以参考nomasp的解析

  • 相关阅读:
    pickle模块使用
    Graphviz安装教程
    Redis常用命令
    MongoDB和Redis的区别
    UVA-1572
    poj2352
    poj1195
    Codeforces Round #430 (Div. 2)
    Codeforces Round #431 (Div. 2) B. Tell Your World
    poj3278 【BFS】
  • 原文地址:https://www.cnblogs.com/liuwfuang96/p/7010640.html
Copyright © 2011-2022 走看看