- 原题链接:11. 盛最多水的容器
1- 思路
双指针法
- 水面的高度是由最短的柱子决定的,所以移动右边那根更高的柱子的时候,水面高度一定是不会增加的,甚至可能遇到更短的柱子而变小,而且宽度有一定减少,所以水的面积也一定减少。
结论:
- 移动两根柱子之间更短的那根柱子,才有可能在宽度一定变小的情况下,找到一个更高的水面,从而使得面积更大。
思路:
- 1.设置两个指针,分别指向容器的两侧,即左指针
left
指向最左边的柱子,右指针right
指向最右边的柱子。 - 2.记录下此时的面积,定义为 res
- 3.观察需要移动的柱子
- ① 如果移动较高的柱子,由于水的宽度在变小,而水的高度不一定会增加,所以最终水的面经不会超过之前记录的水的面积 res
- ② 所以只能移动较短的柱子,然后计算此时水的面积,再与之间记录的水的面积 res 作比较,保存大的值。
- 4.再去判断移动哪个柱子
- 5.直到
left
和right
相遇
2- 实现
⭐11. 盛最多水的容器——题解思路
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length-1;
int res = 0;
while(left < right){
int h = Math.min(height[left],height[right]);
int width = right - left;
int nowArea = h*width;
if(nowArea>res){
res = nowArea;
}
if(height[left]<height[right]){
left++;
}else{
right--;
}
}
return res;
}
}
3- ACM 实现
public class maxArea {
public static int maxAre(int[] height){
// 定义指针
int left = 0;
int right = height.length-1;
int res = 0;
// 2. 遍历
while (left<right){
int h = Math.min(height[left],height[right]);
int width = right - left;
int nowArea = h*width;
if(nowArea>res){
res = nowArea;
}
if(height[left]<height[right]){
left++;
}else {
right--;
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入数组长度");
int n = sc.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n;i++){
nums[i] = sc.nextInt();
}
System.out.println("结果是"+maxAre(nums));
}
}