Leetcode -- Container With Most Water

来源:互联网 发布:软件售后分那些 编辑:程序博客网 时间:2024/05/22 08:06

题目:
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.

分析:若干条线,找两条线使得其与X轴围成的面积最大。
如果是暴力的穷搜,肯定可以得到答案,但复杂度达到O(N^2),耗时,leetcode里面是过不去的。

思路:从数据集的两头同时开始。当ai小于aj时,i ++; 反之,j–。直到二者相遇。理由,影响面积的是比较短的线,因此,每次只要改变比较短的线就好了。这个想法的复杂度是O(N)

代码:

int maxArea(vector<int>& height) {        int len = height.size();        int max_area = 0, area = 0;        int i = 0, j = len - 1;        while(i < j)        {            if(height[i] < height[j])            {                area = (j -i) * height[i];                i ++;            }            else            {                area = (j - i) * height[j];                j --;            }            if (area > max_area)            {                max_area = area;            }        }        return max_area;    }
0 0