11. Container With Most Water LeetCode题解

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.

Subscribe to see which companies asked this question.

题意:

给定n个非负整数a1a2, ..., an,每个代表一个坐标值(i, ai)。n条竖线的两个端点为(i, ai),(i, 0)。找到这样两条线,将他们与x轴一起组成一个容器,使得容器的容积最大。

注:容器不能倾斜,n至少为2


题解:

看到题目,想象出来的画面应该是这样的:


横轴是X轴,假设选取x=1位置和x=4位置的两根棍,则围成的容器如上图所示,蓝色部分为水,水的总体积即容积;

算法应该执行如下:

使用beg和end双指针,beg指针指向数组开头(0), end指向数组末尾(nums.size() - 1)

计算当前容积,更新最大容积大小;

然后比较beg和end中较小的一个,设法将其变大;

(因为容器容积取决于两点:1.两边棍中短的长度;2.两根棍间距;虽然间距持续变小,但是短棍的长度可能变大,总体积也会变大)

变大的方法是:

假设左边,即beg指向的棍短,则beg指针一直向右移动,直至比当前棍子长的位置停下,然后更新容积;(右边则向左边移动)


Code 【Java】

public class Solution {
    public int maxArea(int[] height) {
        int beg = 0;
        int end = height.length - 1;
        int ans = 0;
        while (beg < end) {
            int low = Math.min(height[beg], height[end]);
            ans = Math.max(ans, low * (end - beg));
            while (height[beg] <= low && beg < end) beg++;
            while (height[end] <= low && beg < end) end--;
        }
        return ans;
    }
}

Code【C++】

class Solution {
public:
    int maxArea(vector<int>& height) {
        int beg = 0;
        int end = height.size() - 1;
        int ans = 0;
        while (beg < end) {
            int low = min(height[beg], height[end]);
            ans = max(ans, low * (end - beg));
            while (height[beg] <= low && beg < end) beg++;
            while (height[end] <= low && beg < end) end--;
        }
        return ans;
    }
};



猜你喜欢

转载自blog.csdn.net/baidu_23318869/article/details/72156152