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

来源:互联网 发布:爱普生tx800清零软件 编辑:程序博客网 时间:2024/06/02 19:39

难度: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;    }};


    


原创粉丝点击