11. Container With Most Water

题目描述:

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;
    }
};

心得:

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。