题目:力扣https://leetcode-cn.com/problems/container-with-most-water/
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length-1;
int ans=0;
while(left<right){
int h = height[left]<height[right]?height[left]:height[right];
int v = (right-left)*h;
ans = ans<v?v:ans;
if(height[left]<height[right]){
left++;
}else{
right--;
}
}
return ans;
}
}
思路:这道题leetcode居然将它定为中等题目,但实际做起来并不觉得中等的难度,仅仅一次就AC了,并且最后效果还算不错。由短板效应可知,在取“桶”的高度时需要取两者中较小值。这题求的是最大容积,此处容积的计算计算方法:桶的高度*x轴差值。因此采用双指针的方法解题,初始状态两指针分别处于一头一尾,计算当前时刻的容积大小,使两指针不断靠拢并记录最大容积。两指针靠拢,x轴的插值必定减小,因此为了求最大容积,在移动指针时应先指向对象值较小的指针,以此类推直至两指针相遇,最后返回最大容积即可。
1.声明变量。left为左指针,right为右指针,ans为最大容积。height.length为传入数组的长度。
int left = 0;
int right = height.length-1;
int ans=0;
2.按双指针不断靠拢的方法遍历整个数组,找到最大容积。h为桶高度,v为当前时刻桶的容积,ans为最大容积。if else语句是判断height[left]和height[right]两者那个更小,若前者更小则left++,若后者更小则right--。
while(left<right){
int h = height[left]<height[right]?height[left]:height[right];
int v = (right-left)*h;
ans = ans<v?v:ans;
if(height[left]<height[right]){
left++;
}else{
right--;
}
}
3.完成上述循环后,ans记录的就是当前最大容积,返回ans即可。
return ans;