当前位置:网站首页>【LeetCode】11. 盛最多水的容器 - Go 语言题解
【LeetCode】11. 盛最多水的容器 - Go 语言题解
2022-07-24 06:24:00 【想变厉害的大白菜】
一、题目描述
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 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
提示:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
题目链接:https://leetcode.cn/problems/container-with-most-water/
二、解题思路 - 双指针法
从直觉上来观察:
- 容器的底肯定是越宽越好,这样能容纳更多的水。
- 容器的两壁肯定是越高越好。
- 容器的水量取决于较矮的那个壁。
从第一点直觉出发,我们可以采用 由宽到窄 的搜索方式:用两个指针来表示容器的左右边界,先令其分别指向数组的两端,然后逐步向中间移动搜索,直到两指针相遇。
从第二点直觉出发,我们知道两壁越高越好,那么移动指针的方式就是:移动哪一个指针呢?当前哪一个壁较矮,我们就向前移动指向该壁的指针。
每移动一次,就计算当前容器的最大水量,计算时要注意:容器的有效高度要以比较矮的那个壁为准。
三、我的题解
Go 语言代码:
func maxArea(height []int) int {
i:=0
j:=len(height)-1
max := 0
for i != j {
if height[i]<=height[j]{
if (j-i)*height[i] > max {
max = (j-i)*height[i]
}
i++
}else{
if (j-i)*height[j] > max {
max = (j-i)*height[j]
}
j--
}
}
return max
}
评判结果:
边栏推荐
- You don't have to waste your life on others' standards
- GE口:SGMII模式和serdes模式
- Vs2019 configuration running open3d example
- Redis persistence
- Lambda expressions sort list objects in multiple fields
- Sparksql core usage, 220724,
- Introduction to pyqt5 - student management system
- Requirements already satisfied: and read timed out. problem solving methods appear during the installation of snownlp package
- 2022-07-22 mysql/stonedb parallel hashjoin memory usage analysis
- Day (0~6) represents the starting position of the first day of each month, stop represents the number of days of each month, and there are two blank spaces between each day. Input different days and s
猜你喜欢

STM32 external interrupt (register version)

Redis 哨兵机制

变量和数据类型(03)

C语言中extern,static, register,volatile 关键字的作用;保姆级教学!

【方向盘】超爱的IDEA提效神器Save Actions,卸载了

10分钟就能写出来的——25~30K的国外企业招聘面试考题,这不是轻轻松松吗~

tensorflow einsum函数

Jinan renshe has signed 1w+ electronic labor contract, which greatly helps HR digitalization

C language to achieve three chess? Gobang? No, it's n-chess

It can be written in 10 minutes -- 25~30k foreign enterprise recruitment interview questions, isn't it easy~
随机推荐
Create WPF project
Lambda expressions sort list objects in multiple fields
Wix path with spaces
UE4/5 无法打开文件“xxx.generated.h”(Cannot open file xxx.generated.h)的解决方法总结
【学习笔记】url输入到页面展现中发生了什么?
不要太在意别人对你的看法
树莓派换源
Use of redis
chm文件打开时提示乱码
永远不要迷失自我!
Cmake notes
MySQL gets the self incrementing line mark (different from MySQL version)
一首伟大的赞歌
[waveform / signal generator] Based on stc1524k32s4 for C on Keil
You can't satisfy everyone!
Input some data and find the maximum output. (keyboard and file reading)
tensorflow boolean_ Mask function
Mac can't connect to local MySQL server through socket '/tmp/mysql Sock '(2) problem
tensorflow scatter_ Nd function
【学习笔记】从汇编看 a+++a与 a+a++的区别