当前位置:网站首页>笔试面试题目:盛水最多的容器
笔试面试题目:盛水最多的容器
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
边栏推荐
- Astra: the future of Apache Cassandra is cloud native
- PCR and PTS calculation and inverse operation in TS stream
- shiyou的数值分析作业
- Analysis of ArrayList source code
- 函数周期表丨筛选丨值丨SELECTEDVALUE - 知乎
- SQL Server 2008R2 18456 error resolution
- 虚拟机中安装 macOS 11 big sur
- Improvement of rate limit for laravel8 update
- 211考研失败后,熬夜了两个月拿下字节offer!【面经分享】
- “1024”征文活动结果新鲜出炉!快来看看是否榜上有名?~~
猜你喜欢
随机推荐
Close to the double 11, he made up for two months and successfully took the offer from a large factory and transferred to Alibaba
渤海银行百万级罚单不断:李伏安却称治理完善,增速呈下滑趋势
Six key points of data science interview
Rust:命令行参数与环境变量操作
搜索引擎的日常挑战_4_外部异构资源 - 知乎
laravel8更新之速率限制改进
Bili Bili common API
2020-11-05
Function periodic table filter value selectedvalue
nvm
盘点那些你没想到的云计算应用场景(上)
print( 'Hello,NumPy!' )
架构师(2020年11月)
ArrayList源码分析
计算机网络基本概念(五)局域网基本原理
Dogs can also operate drones! You're right, but it's actually an autonomous drone - you know
[original] about the abnormal situation of high version poi autosizecolumn method
i5 1135g7和i5 1035g1参数对比区别大吗? 哪个好
Python learning Day1 -- Basic Learning
SQL Server 2008R2 18456 error resolution