刷题笔记
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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
思路
- 最容易想到的思路,还是类似于对数组进行一个两层循环的遍历,这样选出容量的最大值,在正确性上是正确的,但是时间耗费太多。
- 换一种一遍两头遍历的思路,即从两侧开始往中间遍历,每次移动的那个选项是二者中比较小的那个。这里移动的目的是为了把这个短板替换掉,因为两个高度中的短板是限制面积的主要因素。
- 所以移动的原则是要找到一个比开始移动的位置的数值大的数。
- 这样移动到最后,遍历所有情况后,自然可以判断留下最大的容量。
代码实现
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int vol = 0;
while (left < right) {
vol = Math.max(vol, Math.min(height[left], height[right]) * (right - left));
if (height[left] < height[right]) {
int temp = height[left];
while (height[left] <= temp && left < right) {
left++;
}
} else {
int temp = height[right];
while (height[right] <= temp && left < right) {
right--;
}
}
}
return vol;
}
}