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

    一开始感觉跟Trapping Rain Water这题很像,就按着那题的想法写了,可是总是WA,后来好好一想发现不对,其实这题比那题还简单一点,想法跟数组中求和为给定值的两数一样。所谓容积其实就是面积,我们都知道长方形的面积=长*宽,不妨我们就从长最长的长方形找起,即令left = 0, right = height.size() - 1,但是在找下一个长方形时,长肯定会变短,要弥补这一段损失就必须加宽宽度,所以一下个就换掉两条宽中较小的那一个。代码也很简单:

     1 class Solution {
     2 public:
     3     int maxArea(vector<int> &height) {
     4         int maxArea = 0, area;
     5         int left = 0, right = height.size() - 1;
     6         while (left < right) {
     7             area = (right - left) * min(height[left], height[right]);
     8             maxArea = (maxArea > area) ? maxArea : area;
     9             if (height[left] < height[right])
    10                 ++left;
    11             else
    12                 --right;
    13         }
    14         return maxArea;
    15     }
    16 };
  • 相关阅读:
    Pytorch 入门之Siamese网络
    Pytorch 之 backward
    非极大值抑制(NMS)
    Apriori 算法python实现
    canny 算子python实现
    转载
    ubuntu 安装lightgbm
    OneHotEncoder独热编码和 LabelEncoder标签编码
    Adroid—— DVM
    PHP——做服务
  • 原文地址:https://www.cnblogs.com/easonliu/p/3656388.html
Copyright © 2011-2022 走看看