力扣十一;乘最多水的容器

题目:乘最多水的容器

题目描述:

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

说明:你不能倾斜容器。

示例 1:

输入:[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

思路:

​ 用到对撞指针的思路,指针开始指向开头和末尾,从开始和末尾分别判断, 如果 (height[end]>height[first]),就first++。

go代码

func maxArea(height []int) int {
    max:=0
    end:=len(height)-1
    first:=0
    var ans int
    for first<end{
        width := end-first
        if(height[end]>height[first]){
            ans=width*height[first]
            first++
        }else{
            ans=width*height[end]
            end--
        }
        if(max<ans){
            max=ans
        }
    }
   return max 
}

代码效率:

执行用时:20 ms, 在所有 Go 提交中击败了83.14%的用户
内存消耗:6.3 MB, 在所有 Go 提交中击败了53.07%的用户


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!