当前位置:网站首页>双指针进阶--leetcode题目--盛最多水的容器

双指针进阶--leetcode题目--盛最多水的容器

2022-04-23 17:22:00 emo~~~~

题目链接

11. 盛最多水的容器 - 力扣(LeetCode) (leetcode-cn.com)icon-default.png?t=M3K6https://leetcode-cn.com/problems/container-with-most-water/这题我第一个想法是滑动窗口算法,因为我曾经深受其益

三连击破---滑动窗口算法---leetcode_emo~~~~的博客-CSDN博客icon-default.png?t=M3K6https://blog.csdn.net/qq_61567032/article/details/123878549?spm=1001.2014.3001.5501就像这样:大家简单

int maxArea(vector<int>& height) {
    int len = height.size();
    int maxx = 0;
    vector<int>ret = height;
    sort(ret.begin(), ret.end());
    int s = ret[len - 1];
    for (int i = len; i > 1; i--)
    {
        int left = 0;
        int right = left + i - 1; 
        while (right <= len - 1)
        {
            int h = min(height[left], height[right]);
            int l = i - 1;  //长度是两线之间空格的个数!!!
            maxx = max(maxx, h * l);
            left++;
            right++;
        }
    }
    if (s >= maxx)
        return s;
    else
        return maxx;
}

简单是简单,看一下时间复杂度,不出意外的超时了!!

 在优化时,不经意想到了双指针,通过双指针的前后遍历可以很快的解决此题;

1、我们还是从长度最长开始,只是不需要每次都判断很多次

2、判断左指针和右指针的大小,每次只移动较小的指针,因为,如果移动大指针,后面的面积只会比现在的更小(很显然,由于长度从大到小,所以大指针只能向左移。如果左移了大指针,容器的长度减小了,但由于现在容器的真实长度(小指针)没有变,所以容器的高度不会增加,所以移动大指针容器的容积只减不增!

3、比较选择容器容积的最大值,当遍历完成之后,即得到答案
 

其实,这题是一道经典的双指针算法题!

int maxArea(vector<int>& height) {
    int len = height.size();
    int left = 0;
    int right = len - 1;
    int maxx = 0;
    while (left <= right)
    {
        int h = min(height[left], height[right]);
        int l = right - left;
        maxx = max(maxx,h * l);
        if (height[left] < height[right])
        {
            left++;
        }
        else
        {
            right--;
        }
    }
    return maxx;
}

int main()
{
    vector<int>height;
    for (int i = 0; i < 2; i++)
    {
        int a = 0;
        cin >> a;
        height.push_back(a);
    }
    int ans = maxArea(height);
    cout << ans;
    return 0;
}

希望和诸君共勉!!! 

版权声明
本文为[emo~~~~]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_61567032/article/details/124360763