前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode】 11. Container With Most Water

【LeetCode】 11. Container With Most Water

作者头像
韩旭051
发布2019-11-08 00:42:34
3050
发布2019-11-08 00:42:34
举报
文章被收录于专栏:刷题笔记

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/shiliang97/article/details/101952213

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.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7] Output: 49

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/container-with-most-water 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

暴力直接过了击败了百分之12的人

代码语言:javascript
复制
class Solution {
public:
    int min(int a,int b){
        if(a>b){
            return b;
        }return a;
    }
    int maxArea(vector<int>& height) {
        int max=-1;
        for(int i=0;i<height.size();i++){
            for(int l=i+1;l<height.size();l++){
                int num=min(height[i],height[l])*(l-i);
                if(num>max){
                    max=num;
                }
            }
        }
        return max;
    }
};

整了个双指针,速度时间一下提升了不少

代码语言:javascript
复制
class Solution {
public:
    int maxArea(vector<int>& height) {
        int a=0,b=height.size()-1;
        int max=-1;
        while(a!=b){
            if(height[a]<=height[b]){
                if(height[a]*(b-a)>max){
                    max=height[a]*(b-a);
                }
                a++;
            }else{
                if(height[b]*(b-a)>max){
                    max=height[b]*(b-a);
                }
                b--;
            }
        }
        return max;
    }
};

看到一段特别有意义的评论

证明很严谨。 其实无论是移动短指针和长指针都是一种可行求解。 只是,一开始就已经把指针定义在两端,如果短指针不动,而把长指针向着另一端移动,两者的距离已经变小了,无论会不会遇到更高的指针,结果都只是以短的指针来进行计算。 故移动长指针是无意义的。

最快的人咋写的?

代码语言:javascript
复制
class Solution {
public:
    int maxArea(vector<int>& height)
    {
        int maxarea = 0, l = 0, r = height.size() - 1;
        while (l < r) {
            int a = height[l] > height[r] ? height[r] : height[l];
            maxarea = maxarea > a * (r - l) ? maxarea : a * (r - l);
            if (height[l] < height[r])
                l++;
            else
                r--;
        }
        return maxarea;      
        
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 暴力直接过了击败了百分之12的人
  • 整了个双指针,速度时间一下提升了不少
    • 看到一段特别有意义的评论
    • 最快的人咋写的?
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档