leetcode——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

         一开始没看懂题目,后来查了网上答案,大概意思是:x轴上在1,2,...,n点上有许多垂直的线段,长度依次是 a1, a2, ..., an。找出两条线段,使他们和x轴围成的面积最大。面积公式是 Min(a i, a j) X |j - i|

思路1:

注意到面积大即容积大,面积由最短高度来决定,要求返回的是最大面积。

一开始想到的就是双重循环,遍历i,j, 但是时间复杂度是O(n²),会超时

class Solution {
public:
    int maxArea(vector<int> &height) {
        // 宽乘以最短木板长度就是最大面积
        // 宽是1,2,3....
        // 时间复杂度O(n²)
        int start(0), end(1); // 记录起始木板的横坐标,两个之差为宽
        int area(INT_MIN);
        for(start = 0; start != height.size(); start++){
            for(end = start+1; end != height.size(); end++){
                area = max(area, min(height[start], height[end]) * (end - start));
            }
        }
        return area;
    }
};

 

image

思路2:

看了大神的答案.

容积即面积,它受长和高的影响,当长度减小时候,高必须增长才有可能提升面积,所以我们从长度最长时开始递减,然后寻找更高的线来更新候补.

class Solution {
public:
    int maxArea(vector<int> &height) {
        // 容积由面积决定
        // 面积由短木板高度决定
        // 当宽度减少时,短木板的高度应该增加,才能保证面积的增加,因此要找到比短木板的高度高的木板
        // 返回最大面积
        int l(0), r(height.size()-1), area(INT_MIN);
        while(l < r){
            area = max(area, min(height[l], height[r]) * (r-l));
            if(height[l] <= height[r]) l++;
            else r--;
        }
        return area;
    }
};

转载于:https://www.cnblogs.com/skysand/p/4298102.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值