LeetCode 11 Container With Most Water

本文介绍了解决LeetCode第11题“盛水最多的容器”的两种方法。该题要求找出能盛最多水的两条线段。解决方案包括了直观但效率较低的双层循环方法和更高效的双指针技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 11

Container With Most Water

  • Problem Description:
    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) 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 and n is at least 2.

  • Solution 1:
    这个解法是最容易想到的==但也是显然超时的,不过通过此解法可以确定自己对题目的理解是正确的,继续往下改善

class Solution {
public:
    int maxArea(vector<int>& height) {
        int max_water = 0;
        for (int i = 0; i < height.size()-1; i++) {
            for (int j = i+1; j < height.size(); j++) {
                int temp = height[i]<height[j]? height[i]:height[j];
                if (temp*(j-i) > max_water)
                    max_water = temp*(j-i);
            }
        }
        return max_water;
    }
};
  • Solution2:
    主要思路:用两个变量left和right标记从数组两边遍历的位置,先计算出当前位置两条line和底边长度(right-left)围成的的面积,然后对其中一条line进行移进操作(判断条件:哪个变量对应的函数值小,就对该line移进使之靠近中心),再次计算围成的面积,比较后取max即可。
class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0;
        int right = height.size()-1;
        int max_water = 0;
        while (left < right) {
            int min_water = height[left]<height[right]? height[left]:height[right];
            int temp = min_water*(right-left);
            if (temp > max_water)
                max_water = temp;
            if (height[left]<height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return max_water;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值