Container With Most Water水箱问题

来源:互联网 发布:电脑版扫描软件 编辑:程序博客网 时间:2024/04/28 09:29


Given n non-negative integersa1, 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.

这题就是要寻找到两个直线,中间的容积最大,容器的宽度就是下标 之差,高度取最短的那个直线:

对于ai,aj,其中i<j,求max (min(ai,aj))*(j-i)

看到题目第一下马上想到的就是暴力求解法:

<span style="font-size:14px;">class Solution {public:    int my_min(int a,int b)    {        return a<b?a:b;    }    int maxArea(vector<int>& height) {        int L = height.size();        int result = 0;        for(int i =0;i<L-1;i++)        {            if(height[i]*(L-1-i)<=result)//剪枝                continue;            for(int j = i+1;j < L;j++)            {                result = (my_min(height[i],height[j])*(j-i))>result?(my_min(height[i],height[j])*(j-i)):result;            }        }        return result;    }};</span>
当然不用想也知道肯定超时。果然那句话:第一个想到的方法往往不是最好的方法。

这时换一个思路:

对于影响结果的几个因素,第一就是宽度,第二就是高度。暴力求解就是从宽度出发,假设只要宽度变宽都是有可能达到最优解的。但是现实中有这样这这样的可能,往后高度越来越小,但是这种情况下还是不能排除某些数据。

如果从高度来讲,最小的高度将影响结果,那我们每一次都调整最短的那个距离。

class Solution {public:    inline int my_min(int a,int b)    {        return a<b?a:b;    }    int maxArea(vector<int>& height)    {        int L = height.size();        int head = 0;        int rear = L-1;        int result = 0;               while(head < rear)        {             result = (my_min(height[head],height[rear])*(rear-head)>result)?(my_min(height[head],height[rear])*(rear-head)):result;             if(height[head] <= height[rear])             {                 ++head;             }             else             {                 --rear;             }        }        return result;    }};

提交运行成功。

0 0
原创粉丝点击