LeetCode 11. Container With Most Water 对撞指针

一。题目:

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 linei 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.

题意:给一组数组整数 a1, a2, ..., an,,作为与Y轴平行的直线。这些竖线与X轴合成一个容器,求出该容器最大的容量

思路1:暴力解法。外围循环从0至size-1。内重循环1至size-1,在此过程中不断更新比较最大容量

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0;
    	int maxCap = 0;
    	while (left<height.size())
    	{
    		int right = height.size() - 1;
    		for (int i = right; i >= 0;i--)
    		{
    			int tempMax = 0;
    			if (height[left]<height[i])
    			{
    				tempMax = height[left] * (i - left);
    			}
    			else
    			{
    				tempMax = height[i] * (i - left);
    			}
    			if (maxCap < tempMax)
    			{
    				maxCap = tempMax;
    			}
    		}
    		left++;
    
    	}
    	return maxCap;
    }
};
其结果就是超时。。。


思路2(这个我没想出来,想过对撞指针不知道怎么处理,智商捉急啊):

        对撞指针:首尾两个索引的值取最小的为容器的高度,可以计算出此时的容量,当左边的值小于等于此时容器的高度直接跳过(表示这些值都在容量内),直到找到一个大于容量高度的值停下来。同样的右边也如此(尽管上一次容器的高度取的是左右两侧小的值,但是当两者相等时就需要在右侧找一个大于当前容器高度的值)。再重新计算容器新的高度,同时计算此时的容量,更新最大容量。

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



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值