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


看到这种题目的第一个想法还是直接循环遍历找最大的,果然,时间复杂度太高了-->time limit exceeded
class Solution {
    //x-axis x轴;slant 倾斜
    //形成的是一个画在纸上的那样的二维的木桶?
public:
    int maxArea(vector<int>& height) {
        int num=height.size();
        if(num==2){
            return min(height[0],height[1]);
        }
        int maxArea=0;
        int area=0;
        for(int i=0;i<num-1;i++){
            for(int j=i+1;j<num;j++){
                area=(j-i)*min(height[i],height[j]);
                maxArea=max(maxArea,area);
                //cout<<i<<"  "<<j<<"  "<<area<<"  "<<maxArea<<endl;
            }
        }
        return maxArea;
    }
};


经典的解法是用两个指针逐渐逼近。
class Solution {
    //x-axis x轴;slant 倾斜
    //形成的是一个画在纸上的那样的二维的木桶?
public:
    int maxArea(vector<int>& height) {
        //这个方法给人的感觉和快速排序的方法很像
        int maxArea=0;
        int tempArea=0;
        //定义int类型的值的默认值居然不是0,吃惊
        //int maxArea,tempArea;
        int start=0;
        int end=height.size()-1;
        while(start<end){
            tempArea=(end-start)*min(height[start],height[end]);
            maxArea=max(maxArea,tempArea);
            //cout<<tempArea<<"  "<<maxArea<<endl;
            if(height[start]>height[end])
                --end;
            else
                ++start;
        }
        return maxArea;
    }
};

因为面积同时受到宽度和最短的高的限制,先从宽度最大的情况开始,假设此时的面积最大,让两条边相对较短的一条向里逼近,继续寻找面积最大的情况。因为如果移动较长的那条边的话,只会越变越短,变长的机会减少。
Initially we consider the area constituting the exterior most lines. Now, to maximize the area, we need to consider the area between the lines of larger lengths. If we try to move the pointer at the longer line inwards, we won't gain any increase in area, since it is limited by the shorter line. But moving the shorter line's pointer could turn out to be beneficial, as per the same argument, despite the reduction in the width. This is done since a relatively longer line obtained by moving the shorter line's pointer might overcome the reduction in area caused by the width reduction.

自己在按照这种思想写的时候仍然出现了小问题,定义变量的时候一定要赋初值,自己以为的默认值不一定靠得住。

https://leetcode.com/problems/container-with-most-water/discuss/6099/yet-another-way-to-see-what-happens-in-the-on-algorithm

迷迷糊糊似懂非懂其中的原理
emmmm 那就是不懂

猜你喜欢

转载自blog.csdn.net/xueying_2017/article/details/79934296