leetcode 11.Container With Most Water

来源:互联网 发布:韩国美女直播秀软件 编辑:程序博客网 时间:2024/05/01 23:20

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.

题目大意:给定一个高度数组,相当于隔板的高度,数组的下标表示其X坐标(这里下标规定从1开始),求任意两隔板间的最大盛水量。

(短板原理,盛水容量为X坐标之差乘以较小隔板的高度)

高度数组首尾两边设一个指针,然后计算area,如果height[i] <= height[j],那么i++,因为在这里height[i]是瓶颈,j往里移只会减少面积,不会再增加area。

这是一个贪心的策略,每次取两边围栏最矮的一个推进,希望获取更多的水。

面积 area = min(height[j], height[i]) * (j-i),当height[i] < height[j]时,此时面积 area = height[i] * (j-i); 由于height[i]是短板,不管跟谁组合,它能达到的最大面积取决于 j-i,而此时j-i的距离是最大的,因此,此面积即为以i为左边界的最大面积,然后++i;同理得j的变化。因为对于i, j,总有一个是短板,每次是短板的就发生变化,因此覆盖了所有情况。

class Solution {public:    int maxArea(vector<int>& height)    {        int max_area = 0;        int area = 0;        int n = height.size();        int left = 0;        int right = n -1;        while(left < right)        {            area = min(height[left],height[right]) * (right - left);            if(area > max_area)            {                max_area = area;            }            if(height[left] < height[right])                left++;            else                right--;        }        return max_area;    }};


0 0
原创粉丝点击