leetcode之Container With Most Water的js实现

原题在这里

简单翻译一下。

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 and n is at least 2.

Tags: Array, Two Pointers

指定n个非负整数,a1,a2,...,an,每个数代表一个坐标(i,ai),用竖线把(i,ai)和(i,0)连接起来,这样在二维坐标系里就形成了一根线。在数轴中找这样两条竖线形成的容器能装最多水。

注意:n >=2,容器不能倾斜。

标签:数组,点。

如果还看不懂,上张图:


本题如果用二重循环去做的话,时间复杂度为O(n^2)。随着问题规模n的增大,时间频度会急剧增长。所以,针对本题,我们采用双指针的方法降低算法的时间复杂度,达到O(n)。

看图中红色的两根竖线,我们可以把这两条竖线想象成双指针i和j。当指针所指位置的两条竖线(ai,aj)按题意形成容器s1的时候,temp = Math.min(ai,aj)。先移动指针i,直到找到比temp大的值am,再移动指针j,直到找到比temp大的值an,am和an形成容器s2,max = Math.max(s1,s2)。继续比较,直到j >= i跳出循环。

下面上段代码:

function maxArea(arr) {
    var l = 0, r = arr.length - 1;
    var max = 0, h = 0;
    while (l < r) {
        h = Math.min(arr[l], arr[r]);
        max = Math.max(max, (r - l) * h);
        while (arr[l] <= h && l < r) ++l;
        while (arr[r] <= h && l < r) --r;
    }
    return max;
}
这里指针i和指针j同时移动,提高了算法的效率。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值