您的位置:首页 > 大数据 > 人工智能

11. Container With Most Water LeetCode题解

2017-05-15 16:23 886 查看
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.

Subscribe to see which companies asked this question.
题意:
给定n个非负整数a1, a2,
..., 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息