盛最多水的容器

题目链接:https://leetcode-cn.com/problems/container-with-most-water
题目描述:
给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。

题解:
双指针法,容纳的水量是由两个指针指向的数字中较小值 * 指针之间的距离。每次移动值较小的那个指针。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int length = height.size();
        int i = 0;
        int j = length - 1;
        int width = length - 1;
        int result = 0;
        while(i < j)
        {
            result = max(result, min(height[i], height[j]) * width);
            width--; 
            if(height[i] <= height[j])
            {
                i++;  
            }else{
                j--;
            }
        }
        return result;
    }
};

原文地址:https://www.cnblogs.com/ZigHello/p/15020133.html