【Hot100】LeetCode—11. 盛最多水的容器



1- 思路

双指针法

  • 水面的高度是由最短的柱子决定的,所以移动右边那根更高的柱子的时候,水面高度一定是不会增加的,甚至可能遇到更短的柱子而变小,而且宽度有一定减少,所以水的面积也一定减少。

结论:

  • 移动两根柱子之间更短的那根柱子,才有可能在宽度一定变小的情况下,找到一个更高的水面,从而使得面积更大。

思路:

  • 1.设置两个指针,分别指向容器的两侧,即左指针 left 指向最左边的柱子,右指针 right指向最右边的柱子。
  • 2.记录下此时的面积,定义为 res
  • 3.观察需要移动的柱子
    • ① 如果移动较高的柱子,由于水的宽度在变小,而水的高度不一定会增加,所以最终水的面经不会超过之前记录的水的面积 res
    • ② 所以只能移动较短的柱子,然后计算此时水的面积,再与之间记录的水的面积 res 作比较,保存大的值。
  • 4.再去判断移动哪个柱子
  • 5.直到 leftright 相遇

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));
    }
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值