当前位置:网站首页>leetcode.11 --- 盛最多水的容器

leetcode.11 --- 盛最多水的容器

2022-06-22 18:45:00 _End丶断弦

盛最多水的容器

在这里插入图片描述

暴力解法:
在这里插入图片描述
2层for循环,时间复杂度n方,本题会直接超时

代码如下:

class Solution {
    
public:
    int maxArea(vector<int>& height) {
      
        int res = 0;
        for(int i=0;i<height.size();i++)
        {
    
            for(int j=i+1;j<height.size();j++)
            {
    
                res = max(res,min(height[j],height[i])*(j-i));
            }
        }

        return res;
    }
};

解法二:
双指针解法,直接看题解,每次短的向前一步

代码如下:

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

时间复杂度:O(n)

为什么双指针可以解决,可以看题解给出的证明即可。

原网站

版权声明
本文为[_End丶断弦]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45599288/article/details/125402380