题目

给定 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

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/WilsonPan/p/11840850.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!