leetcode——Container With Most Water

来源:互联网 发布:as3.0调用js页面方法 编辑:程序博客网 时间:2024/06/08 16:31

题目:

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 linei 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.

class Solution {public:    int maxArea(vector<int>& height) {       int i = 0, j = height.size() - 1;//维护两个指针,分别向中间靠拢,更新最大面积       int max_area = 0;       while (i < j)        {           int area = (j - i) * min(height[i], height[j]);           max_area = max(area, max_area);           if (height[i] < height[j])//每次更新较短的线段,因为更新较大的线段必然造成面积变小           {               ++i;           }           else           {               --j;           }       }       return max_area;    }};


0 0
原创粉丝点击