当前位置:网站首页>笔试面试题目:盛水最多的容器
笔试面试题目:盛水最多的容器
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
边栏推荐
- Basic concepts of computer network (5) basic principles of local area network
- 盘点那些你没想到的云计算应用场景(上)
- 【原创】关于高版本poi autoSizeColumn方法异常的情况
- C++在C的基础上改进了哪些细节
- SQL Server 2008R2 18456 error resolution
- Rust:命令行参数与环境变量操作
- If you don't understand the gap with others, you will never become an architect! What's the difference between a monthly salary of 15K and a monthly salary of 65K?
- 狗狗也能操作无人机!你没看错,不过这其实是架自动驾驶无人机 - 知乎
- VC + + specified directory file output by time
- YGC问题排查,又让我涨姿势了!
猜你喜欢

C++在C的基础上改进了哪些细节

Flink's sink: a preliminary study

Is there a big difference between i5 1135g7 and i51035g1? Which is better?

If you don't understand the gap with others, you will never become an architect! What's the difference between a monthly salary of 15K and a monthly salary of 65K?

Python learning Day1 -- Basic Learning

PCIe enumeration process

That's what software testing is all about?!

Python loop distinction (while loop and for loop)

Face recognition: attack types and anti spoofing techniques

PCR and PTS calculation and inverse operation in TS stream
随机推荐
Basic concepts of computer network (5) basic principles of local area network
Game optimization performance (11) - Zhihu
Julia 是如何风靡起来的?
【计算机网络】学习笔记,第三篇:数据链路层(谢希仁版)
你搞不懂与别人的差距,永远成不了架构师!月薪15K和月薪65K,你差在那了?
Function periodic table filter value selectedvalue
解决Safari浏览器下载文件文件名称乱码的问题
What details does C + + improve on the basis of C
Daily challenges of search engines_ 4_ External heterogeneous resources - Zhihu
2020-11-05
python_ scrapy_ Fang Tianxia
Which is more worth starting with the difference between vivos7e and vivos7
5g/4g工业无线路由器
Solve the problem of rabbitmq message loss and repeated consumption
2 days, using 4 hours after work to develop a test tool
laravel8更新之速率限制改进
Tiktok live monitoring Api: random recommendation
Cloud Alibabab笔记问世,全网详解仅此一份手慢无
双向LSTM在时间序列异常值检测的应用
An error occurred while starting the kernel was successfully resolved