当前位置:网站首页>笔试面试题目:盛水最多的容器
笔试面试题目:盛水最多的容器
2020-11-08 10:30:00 【osc_1ajf1srl】
原文发表于:

今天周末,来看G公司的一道面试题:
求max{|i-j|*min{a[i], a[j]}}的值,其中a是正整数数组,i和j的区间为[0, n-1].
这其实就是leetcode中的“盛水最多的容器”,如下:

鲁迅说:暴力可以解决一切问题。
胡适说:暴力能解决的问题,都不是问题。
因为i和j的可能性是有限组合,所以暴力算法能得到结果,但无法通过面试。
用动态规划吗?貌似也不好动态规划。

![]()
我们可以采用双指针,分别指向头尾,计算出盛水值。然后向中间搜索,尝试找出更大的盛水可能性。
木桶理论告诉我们:对于两块确定的盛水挡板而言,盛水的多少是由短板决定的。
所以,在向中间搜索时,从短板侧向中间移动指针,才有可能产生更大的盛水值。
这是一个核心结论。
至于代码,很简单,来看下:
func maxArea(a []int) int {
n := len(a)
if n < 2 {
return 0
}
if n == 2 {
return min(a[1], a[0])
}
max := min(a[n - 1], a[0]) * (n - 1)
i := 0
j := n - 1
for i < j {
if a[i] < a[j] {
i++
}else {
j--
}
area := min(a[i], a[j]) * (j - i)
if area > max {
max = area
}
}
return max
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
结果:

该算法能正常通过面试,祝大家获得自己心仪的offer.
周末愉快。
版权声明
本文为[osc_1ajf1srl]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4272693/blog/4707996
边栏推荐
- 5g + Ar out of the circle, China Mobile Migu becomes the whole process strategic partner of the 33rd China Film Golden Rooster Award
- Solve Safari browser download file name garbled problem
- An error occurred while starting the kernel was successfully resolved
- 来自不同行业领域的50多个对象检测数据集
- 年轻一代 winner 的程序人生,改变世界的起点藏在身边
- Mate 40 series launch with Huawei sports health service to bring healthy digital life
- Function periodic table filter value selectedvalue
- PCIe 枚举过程
- Architect (November 2020)
- next.js实现服务端缓存
猜你喜欢

How can a technician take over a complex system?

将“光头”识别为“足球”,AI 摄像头如何犯的错?

技术人员该如何接手一个复杂的系统?

Close to the double 11, he made up for two months and successfully took the offer from a large factory and transferred to Alibaba

Unparseable date: 'Mon Aug 15 11:24:39 CST 2016',时间格式转换异常

Solve the problem of rabbitmq message loss and repeated consumption

SQL Server 2008R2 18456错误解决方案

What details does C + + improve on the basis of C

Unparseable date: 'mon Aug 15 11:24:39 CST 2016', time format conversion exception

VC + + specified directory file output by time
随机推荐
sed之查找替换
Python3.9的7个特性
FORTRAN77从文件中读入若干数据并用heron迭代公式开方
5g + Ar out of the circle, China Mobile Migu becomes the whole process strategic partner of the 33rd China Film Golden Rooster Award
SQL Server 2008R2 18456错误解决方案
print( 'Hello,NumPy!' )
TCP协议如何确保可靠传输
维图PDMS切图软件
PX4添加新的应用
洞察——风格注意力网络(SANet)在任意风格迁移中的应用
What is the difference between vivoy73s and vivoy70s
Bili Bili common API
虚拟机中安装 macOS 11 big sur
解决RabbitMQ消息丢失与重复消费问题
Spotify是如何推动数据驱动决策的?
墨者学院SQL注入解题
比Python快20%,就问你兴不兴奋?
AMD Zen3首发评测:频率超5GHz,IPC提升不止19%,这次真的Yes了 - 知乎
laravel8更新之速率限制改进
我们采访了阿里云云数据库SQL Server的产品经理,他说了解这四个问题就可以了...