【LeetCode】11. 盛最多水的容器

一、题目描述

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

说明:你不能倾斜容器,且 n 的值至少为 2。
question_11
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例:

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

二、题目分析

原则:本题符合木桶理论,最短的木板决定桶容量。
思路1:暴力破解法,循环计算所有可能的容量组合,存储在数组中,最后筛选出最大的,复杂度太高,肯定不是好的解决方法,放弃;
思路2:双指针法,采用首尾指针,通过比较首尾数字的大小(木板长短),不停的根据策略(比较指针指向数据的大小,左小则左指针右移,右小则右指针左移)向中间逼近,直到指针相遇,此过程已经覆盖了可能的最大值,通过临时变量保存最大值即可。

三、代码实现

// leetcode_11. 盛最多水的容器
// 非最优代码方案,欢迎继续优化
package main

import "fmt"

func maxArea(height []int) int {
	max := 0
	i := 0
	j := len(height) - 1

	for {
		if j <= i {
			break
		}
		
		tmpMax := 1
		if height[i] <= height[j] {
			tmpMax = height[i]
			i++
		} else if height[i] > height[j] {
			tmpMax = height[j]
			j--
		}

		tmpMax = tmpMax * (j - i + 1)

		if max < tmpMax {
			max = tmpMax
		}
	}

	return max
}

func main() {
	height := []int{1, 2}
	fmt.Println("arr: ", height, "  maxArea: ", maxArea(height))

	height = []int{1, 1}
	fmt.Println("arr: ", height, "  maxArea: ", maxArea(height))

	height = []int{3, 1, 2, 3}
	fmt.Println("arr: ", height, "  maxArea: ", maxArea(height))

	height = []int{1, 8, 6, 2, 5, 4, 8, 3, 7}
	fmt.Println("arr: ", height, "  maxArea: ", maxArea(height))
}

打印结果

arr:  [1 2]   maxArea:  1
arr:  [1 1]   maxArea:  1
arr:  [3 1 2 3]   maxArea:  9
arr:  [1 8 6 2 5 4 8 3 7]   maxArea:  49

Process finished with exit code 0

——2019-07-12——

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值