leetcode 849. Maximize Distance to Closest Person
In a row of seats
, 1
represents a person sitting in that seat, and 0
represents that the seat is empty.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to closest person.
Example 1:
Input: [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
Example 2:
Input: [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat, the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
Note:
1 <= seats.length <= 20000
seats
contains only 0s or 1s, at least one0
, and at least one1
.
里面陷进比较多,面试的话还是要自己写完备的测试用例才行。
直接贪心求解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Solution( object ): def maxDistToClosest( self , seats): """ :type seats: List[int] :rtype: int """ # find max contineous 0, postion i = 0 l = len (seats) ans = 0 while i < l: while i<l and seats[i] = = 1 : i + = 1 # i == l or seats[i] == 0 start = i while i<l and seats[i] = = 0 : i + = 1 # i == l or seats[i] == 1 if start = = 0 or i = = l: ans = max (ans, i - start) else : if (i - start) & 1 : # zero cnt is odd ans = max (ans, (i - start) / 2 + 1 ) else : ans = max (ans, (i - start - 1 ) / 2 + 1 ) #i += 1 return ans |
如果是基于计数器的思维,则写起来也还行吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public int maxDistToClosest( int [] seats) { int dist = 0 ; int temp = 0 ; boolean closed = false; for ( int i = 0 ; i<seats.length; + + i){ if (seats[i] = = 0 ) + + temp; else { dist = Math. max (dist, closed ? ( int )Math.ceil(temp / 2.0 ) : temp); closed = true; temp = 0 ; } } dist = Math. max (dist, temp); return dist; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-07-10 word2vec (一) 简介与训练过程概要