zoukankan      html  css  js  c++  java
  • 【LeetCode】11. 盛最多水的容器

    题目

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

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

     

    图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

     示例

    输入: [1,8,6,2,5,4,8,3,7]
    输出: 49

    解题

    题目意思需要找到两个点,使得容量最大
    我们知道,能装最大的水是由最矮的高度决定
    假设i,k是结果
    maxArea = Min(i, k) * (k - i)

    一、暴力解法

    循环每种可能性,记录最大容量返回,需要两重循环,所以时间复杂度:O(n * n)
    public int MaxArea(int[] height)
    {
        if (height.Length <= 1) return 0;
    
        int max = 0;
        for (int i = 0; i < height.Length; i++)
        {
            for (int k = i + 1; k < height.Length; k++)
            {
                int area = System.Math.Min(height[i], height[k]) * (k - i);
    
                max = System.Math.Max(area, max);
            }
        }
        return max;
    }
    View Code

     

    这个算法真的很慢

    二、双向指针

    设left = 0 , right = length - 1 计算容量

    若left 比 right 矮(height[left] < height[right]) left++,反之 right--

    我们知道容量有2个因素引起,高度 * 宽度,左边指针移动或右边移动都会减少宽度

    只需要遍历一次数组,时间复杂度:O(n)

    public int MaxArea(int[] height)
    {
        int maxArea = 0;
    
        for (int left = 0, right = height.Length - 1; left < right;)
        {
            int area = System.Math.Min(height[left], height[right]) * (right - left);
            maxArea = System.Math.Max(area, maxArea);
    
            if (height[left] < height[right]) left++;
            else right--;
        }
    
        return maxArea;
    }
    View Code

     

    比算法一快了10倍


    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-integer

  • 相关阅读:
    Golang实现mysql where in 查询
    Golang终止程序运行(类似php die; exit;)和打印变量(print_r)
    (转)Unity中protobuf的使用方法
    (转)PlayerPrefs游戏存档
    Unity3d---> IEnumerator
    (转)Unity3D占用内存太大的解决方法
    UICamera(NGUI Event system)原理
    NGUI诡异的drawCall
    (转)U3D DrawCall优化手记
    (转)Unity3D
  • 原文地址:https://www.cnblogs.com/WilsonPan/p/11840850.html
Copyright © 2011-2022 走看看