题目原址
https://leetcode.com/problems/container-with-most-water/description/
题目描述
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.
解题思路
给定一个数组,其中数组在下标i处的值为height[i]
,坐标(i,height[i])
与坐标(j,height[j])构成一条垂直于坐标轴x的直线,现在取两条垂涎和x轴组成四边形容器,问其中盛水量最大为多少?
使用双指针解决该题。
容器能容纳的最多的水应该取决于两个垂直x的直线中最短的那条直线和底边的长度。因此只有较短边会对盛水量由影响,因此移动较短边的指针,并且比较当前盛水量和当前最大盛水量。知道左右指针相遇为止。
假设左边指针left
和右边指针right
,且left指向的值小于right的值,假如我们移动右边指针,则有指针左移后的值和左指针右移的值相比有三种情况
右指针指向的值大于左指针指向的值
- 这种情况下,容器的高取决于左指针,但是底边变短了,所以容器盛水量减小
右指针指向的值等于左指针指向的值
- 这种情况下,容器的高取决于左指针,但是底边变短了,所以容器盛水量减小
右指针指向的值小于左指针
- 这种情况下,容器的高取决于右指针,右指针小于左指针,且底边变短了,所以容器盛水量一i的那个变小了。
所以综上所述,要移动边小的那个指针。直到两个指针相遇
AC代码
class Solution {
public int maxArea(int[] height) {
int sum = 0;
int right = height.length - 1;
int left = 0;
while(left < right) {
sum = Math.max(sum, Math.min(height[left], height[right]) * (right - left));
if(height[left] < height[right])
left ++;
else
right --;
}
return sum;
}
}