zoukankan      html  css  js  c++  java
  • 盛最多水的容器

    问题:

    给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

    说明:你不能倾斜容器,且 n 的值至少为 2。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/container-with-most-water

    方法一:暴力法  时间复杂度 O(n^2)

    /**
     * @param {number[]} height
     * @return {number}
     */
    var maxArea = function(height) {
        let res = -Infinity;
        for(let i=0;i<height.length;i++){
            for(let j=height.length-1;j>=0;j--){
                let h = Math.min(height[i],height[j]);
                res = Math.max(h*(j-i),res);
            }
        }
        return res;
    };

     方法二:双指针法

    /**
     * @param {number[]} height
     * @return {number}
     */
    var maxArea = function(height) {
        let res = -Infinity;
        let left = 0;
        let right = height.length-1;
        while(left<right){
            res = Math.max(Math.min(height[left],height[right])*(right-left),res);
            if(height[left]>height[right]){
                right--;
            }else{
                left++;
            }
        }
        return res;
    };

    时间复杂度:O(n)

  • 相关阅读:
    xml配置文件使用-读取、转换
    .NET 4.0 缓存
    jQuery分页插件pagination.js 笔记
    Spring源码
    Shell编程(字符串篇)
    Linux DNS 相关
    Shell将命令执行结果写入文件
    Linux安装GCC
    Linux网络安全
    产品经理基础
  • 原文地址:https://www.cnblogs.com/ZLDJ-15-516/p/11087963.html
Copyright © 2011-2022 走看看