Leetcode_11 Container With Most Water

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.

Note: You may not slant the container and n is at least 2.
Seen this question in a real interview before?

题目意思:就是在一个二维平面上给你很多点,点 组成是(i,a[i]),其实就是代表一条和(i,0)组成的直线,然后要你选取两条直线,使得能够盛的水最多。其实水盛的多不多取决于那根短的(一个哲理哈哈哈 )。
首先我们看两个性质

(1)首先如果能盛最多的水的是l和r两个点,那么有一个性质,在r的右边绝对不可能存在一个点k,其高度比height[r]大的点,因为如果存在,(k-l)*min(height[l],height[k])会大于(r-l)*min(height[l],height[r])
(2)同理在l的左边不可能存在一个点k 高度大于height[l],所以能盛最多水的肯定在l和r的区间内。
(3)所以初始化l和r在两个端点,然后取短的那边向对面移动,遍历一遍就可以最大的。这就是two pointer的思想。

代码:

class Solution {
public:
    int maxArea(vector<int>& height) 
    {
        int cnt = height.size();
        int max_water = -1;
        int l = 0,r = cnt-1;
        while(l<r)
        {
            int temp = min(height[r],height[l])*(r-l);
            if(temp>max_water)  max_water = temp;
            if(height[r]<height[l])  r--;
            else l++;
        }
        return max_water;
    }
};

猜你喜欢

转载自blog.csdn.net/u014303647/article/details/80412661
今日推荐