LeetCode 11. Container With Most Water

本文详细解析了LeetCode上的经典算法题——容器盛水问题,介绍了一种双指针法来寻找能盛最多水的两个垂直线。通过比较左右两侧的高度,决定移动哪一侧的指针,从而达到O(n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分析

思路
//左侧从左向右,右侧从右向左
//如果左侧比右侧低,则左侧右侧之间的节点与左侧节点之间面积不必计算;//容器高度按左侧计算,宽度不及到右侧的宽度//可直接左侧右移
//如果右侧比左侧低,则左侧右侧之间的节点与右侧节点之间面积不必计算。//可直接右侧左移

难度 Medium

来源 https://leetcode.com/problems/container-with-most-water/

题目

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.

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

解答

package LeetCode;

public class M11_ContainerWithMostWater {
    /*public int maxArea(int[] height){
        int len=height.length;
        int max=0;
        for(int i=0;i<len-1;i++){
            for(int j=i+1;j<len;j++){
                int area=(j-i)*(Math.min(height[i],height[j]));//矩形面积
                if(max<area)
                    max=area;
            }
        }
        return max;
    }*/
  
    public int maxArea(int[] height){
        int len=height.length;
        int max=0,h=0,w=0;
        for(int i=0,j=len-1;i<j;){
            w=j-i;
            if(height[i]<height[j]){
                h=height[i];
                i++;
            }  else {
                h=height[j];
                j--;
            };
            int area=w*h;//矩形面积
            if(max<area)
                max=area;
        }
        return max;
    }
    public static void main(String[] args){
        M11_ContainerWithMostWater m11=new M11_ContainerWithMostWater();
        int[] input1={1,8,6,2,5,4,8,3,7};
        int[] input2={2,3,4,5,18,17,6};
        System.out.println(m11.maxArea(input2));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值