力扣 hot100 Day5

11. 盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

说明:你不能倾斜容器。

//自己写的
class Solution {
public:
    int maxArea(vector& height) {
        int result=0,water=0;
        int n = height.size();
        for(int i =0;iresult)
            {
                for(int j= i+1;j

暴力解法,直接两重嵌套遍历所有可能性。直接遍历提交会超时,这里简单进行了剪枝,如果height[i]过低,无论横坐标多长都无法装更多水,则直接跳过内层循环。处理后可以勉强通过。

//ai提示写的
class Solution {
public:
    int maxArea(vector& height) {
        int result=0,water=0;
        int n = height.size();
        int i =0,j = n-1;
        while(i=height[j])
                j--;
            else
                i++;
        }
        return result;
    }
};

双指针法,用两个指针从两边逼近。逼近逻辑是,移动height较小的一边,可以描述为:舍弃较短边,寻找更高边界。实际上,当ij距离最远时,如果不改变最小边,那么水量将永远被限制,所以舍弃较短边相当于剪枝了一半的变化可能,从而大大提升了时间效率。

你可能感兴趣的:(Hot100,leetcode,算法)