zoukankan      html  css  js  c++  java
  • [leetCode]11. 盛最多水的容器

    题目

    链接:https://leetcode-cn.com/problems/container-with-most-water

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

    说明:你不能倾斜容器。

    在这里插入图片描述

    输入:[1,8,6,2,5,4,8,3,7]
    输出:49 
    解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
    示例 2:
    
    输入:height = [1,1]
    输出:1
    示例 3:
    
    输入:height = [4,3,2,1,4]
    输出:16
    示例 4:
    
    输入:height = [1,2,1]
    输出:2
     
    
    提示:
    
    n = height.length
    2 <= n <= 3 * 104
    0 <= height[i] <= 3 * 104
    

    双指针

    思路: 使用左右指针分别指向容器两遍的边界,每次移动高度较小的指针,因为移动高度交大的指针不会是容器的盛水量变大。在指针移动过程中计算容量,保存最大值。

    class Solution {
        public int maxArea(int[] height) {
            int left = 0, right = height.length - 1;
            int max = 0;
            while (left < right) {
                max = Math.max(max, Math.min(height[left], height[right]) * (right - left));
                if (height[left] < height[right]) {
                    left++;
                    
                } else {
                    right--;
                }
            }
            return max;
        }
    }
    
  • 相关阅读:
    nginx公网IP无法访问浏览器
    Internet接入方式
    Adobe Photoshop Lightroom 5.3和序列号
    getopt
    printf
    scanf
    cycling -avoid the vicious cycle
    ACE handle_timeout 事件重入
    Linux查看程序端口占用
    The GNU C Library
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13942520.html
Copyright © 2011-2022 走看看