LeetCode OJ 之 Container With Most Water(能装最多水的容器)

题目:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

给定非负整数组a1, a2, ..., an,,每一个代表坐标点(i, ai)。坐标点(i, ai) 和 (i, 0)形成了一条垂直于 x 轴的线段,找到两条这样的线段与 x 轴形成一个容器,使得容器能装最大容量的水。注意:不能倾斜容器。

思路:

两个指针,一个指向头一个指向尾,前面的指针向后移动,后面的指针向前移动。

代码:

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

用while替换do while:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值