美文网首页
11. Container With Most Water

11. Container With Most Water

作者: gpfworld | 来源:发表于2018-11-30 10:38 被阅读0次

题目描述:

https://leetcode.com/problems/container-with-most-water/

解决方法:

https://leetcode.com/problems/container-with-most-water/solution/

mycode(c++):

approach1:brute

class Solution {
public:
    int maxArea(vector<int>& height) {
        int max_area = 0;
        for( int i = 0;i<height.size()-1;i++)
            for( int j = i+ 1;j< height.size();j++) {
                int area = (j - i) * min(height.at(i), height.at(j));
                if (area > max_area)
                    max_area = area;
            }
        return max_area;
    }
};

approach2:(two pointer)

class Solution {
public:
    int maxArea(vector<int>& height) {
        int max_area = 0;int l = 0 ,r = height.size()-1;
        while(l < r ){
            max_area = max(max_area,min(height.at(r),height.at(l))*(r-l));
            if(height.at(l)<height.at(r))
                l++;
            else
                r--;
        }
        return max_area;
    }
};

心得:

主要还是要具体问题具体分析,根据实际问题分析。

相关文章

网友评论

      本文标题:11. Container With Most Water

      本文链接:https://www.haomeiwen.com/subject/kdpccqtx.html