leetcode习题解答:11. Container With Most Water

难度:Medium

链接

描述:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

注:返回的是最大面积


解题思路:

第一个想到的就是列举了吧,双重循环来找这个最大面积,当然,这样时间复杂度为O(n^2),耗时感人。下面有一个稍微改进的,二层循环从数组尾端向前扫描,可以排除一些情况,加快速度。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int max = 0;
        for(int i = 0; i < height.size(); i++){
            int h = 0;
            for (int k = height.size()-1; k >= i+1; k--){
                if (height[k] > height[i]){
                    int m = height[i]*(k-i);
                    if (m > max)max = m;
                    break;
                } else if (height[k] > h){
                    int h = height[k];
                    int m = h*(k-i);
                    if (m > max)max = m;
                }
            }
        }
        return max;
    }
};

但是这肯定不是最好的算法,可以有这么一种思路,从数组两端向中间逼近,但是要怎样设置条件呢?

我们知道计算面积,height取的是两边的最小值,那么如果出现一边比较高的时候比如height[left] > height[right],left可以不改动,而right--来寻找一个更高的height,如果right

比较高,那么left++去寻找一个更高的height,这样不断计算面积,最后就能得出最大面积。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0;
        int right = height.size()-1;
        int max = 0;
        while(left < right){
            int  minHeight = height[left]<height[right]?height[left]:height[right];
            int newMax = (right-left)*minHeight;
            if (newMax > max) max = newMax;
            if (height[left] < height[right])
                left++;
            else
                right--;
        }
        return max;
    }
};


    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值