leetcode(1)container-with-most-water

针对给定的高度数组,本文探讨如何找到两个垂直线与x轴构成的最大面积(体积)。通过对比暴力解法与贪心算法,最终实现O(n)的时间复杂度解决此问题。

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

题目 :container-with-most-water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.


理解:随机给了一个数据表示高度,序号表示横坐标。确定两条线和X轴所成的木桶体积最大。


思路:
1.暴力算法,O(n^2),时间不过关
2. 贪心算法(只求当前更好的解,不考虑全局)
 两边设立指针ij 从两侧向中间逼近,若左边矮,向右移,若右边矮小向左移。(最短板效应)


代码:

public class Solution {
    public int maxArea(int[] height) {
        int i=0,j=height.length-1,v=0,v_max=0;
        while(i<j){
        v=Math.min(height[i],height[j])*(j-i);
        v_max=Math.max(v,v_max);
        if(height[i]<height[j])
            {
            i++;
        }
        else
            {
            j--;
        }
    }
        return v_max;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值