leetcode 11. Container With Most Water

来源:互联网 发布:淘宝标题营销词位置 编辑:程序博客网 时间:2024/06/05 16:06



class Solution {public:    int ans(vector<int>&height){        if(height.size() < 2) return 0;        vector<int> up;        up.push_back(0);        int ans = 0;        for(int i = 1;i < height.size(); i++){            if(height[i] > height[up[up.size()-1]])                up.push_back(i);            int low = 0,high = up.size()-1;            while(low <= high){                int mid = (low+high)/2;                if(height[up[mid]] < height[i]) low = mid+1;                else high = mid-1;            }            if(low != up.size()){                ans = max(ans,(i-up[low])*height[i]);            }        }        return ans;    }    int maxArea(vector<int>& height) {        int ans1 = ans(height);        int n= height.size();        for(int i = 0;i < n/2; i++){            swap(height[i],height[n-i-1]);        }        ans1 = max(ans1,ans(height));        return ans1;    }};

class Solution {public:    int up[100000];    int down[100000];    int ans(vector<int>&height){        if(height.size() < 2) return 0;        int top = 0,tail=0;        up[top++] = 0;        int ans = 0;        for(int i = 1;i < height.size(); i++){            if(height[i] > height[up[top-1]])                up[top++] = i;        }        int f = -1;        int top2 = 0,tail2=0;        for(int i = height.size()-1;i>0;i--){            if(height[i] <= f) continue;            f = height[i];            down[top2++] = i;            while(up[top-1] >= i && top > tail) top--;            while(height[up[tail]] < f && tail < top) tail++;            if(tail < top && ans < f * (i-up[tail]))                ans = f*(i-up[tail]);        }        f = -1;        for(int i = 0;i < height.size()-1; i++){            if(height[i] <= f) continue;            f = height[i];            while(down[top2-1]<=i&&top2>tail2)top2--;            while(height[down[tail2]] < f && tail2 < top2) tail2++;            if(tail2 < top2){                ans = max(ans,f*(down[tail2]-i));            }        }        return ans;    }    int maxArea(vector<int>& height) {        int ans1 = ans(height);        return ans1;    }};


0 0
原创粉丝点击