题目来源:https://leetcode.com/problems/container-with-most-water/
问题描述
11. Container With Most Water
Medium
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). nvertical 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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
------------------------------------------------------------
题意
给定一组长度各异的线段,两个线段之间可以构成一个矩形,矩形的高度是较短的那个线段的高度,矩形的宽度是两个线段之间的距离,求矩形的最大面积。
------------------------------------------------------------
思路
维护两个指针l和r,分别从最左端和最右端开始向中间移动。注意到如果两指针指向线段较长的那个指针向中间移动,则得到的矩形一定比原矩形小,因此每次移动时只能移动指向线段较短的指针,直到两指针重合。在指针移动的过程中更新矩形的最大面积。复杂度为O(n).
暴力法也能通过(见注释掉的代码),复杂度为O(n^2).
------------------------------------------------------------
代码
class Solution {
public int maxArea(int[] height) {
// int vol = 0, i = 0, j = 0, n = height.length, cur = 0;
// for (i=0; i<n-1; i++)
// {
// for (j=n-1; j>i; j--)
// {
// cur = Math.min(height[i], height[j]) * (j - i);
// vol = cur > vol ? cur : vol;
// }
// }
// return vol;
int n = height.length, l = 0, r = n - 1, cur = 0, vol = 0;
while (l < r)
{
cur = Math.min(height[l], height[r])*(r-l);
vol = cur > vol ? cur : vol;
if (height[l] < height[r])
{
l++;
}
else
{
r--;
}
}
return vol;
}
}