leetcode解法: Container With Most Water (11)

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.

解法1: Two pointers, O(N) Time, One pass

比较典型的two pointers的题目. 主要思路是, 一个container的面积是(right- left) * (左右两块挡板较短的那一块的长度)
那么要maximize一个面积,可以做的是增长距离,或者是增长板的长度.
设两个指针,从左右边界开始,这个时候,我们的长度是最长的.计算一下当前的面积
如果要提高这个面积, 因为只能缩小长度,则我们必须要提高短板的长度.
那么不停的移动左右指针(哪一根指针指向的板较短就移哪一根)
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int maxArea(vector<int>& height) {
int area = INT_MIN;
int left = 0, right = height.size() - 1;
while (left < right) {
area = max(area, (right - left) * (min(height[left], height[right])));
if (height[left] <= height[right]) {
++left;
} else {
--right;
}
}
return area;
}
};

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int maxArea(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int area = Integer.MIN_VALUE;
int left = 0, right = height.length - 1;
while (left < right) {
area = Math.max(area, (right - left) * (min(height[left], height[right])))'
if (height[left] < height[right]) {
++left;
} else {
--right;
}
}
return area;
}
}