Maximize Distance to Closest Person
Easy
In a row ofseats
,1
represents a person sitting in that seat, and0
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:
Example 2:
Note:
1 <= seats.length <= 20000
seats
contains only 0s or 1s, at least one0
, and at least one1
Analysis
用 Two Pointer解法,time - O(N), space O(1)
Solution
Two Pointer - left, i
left - 为左侧为1的位置下标,i不断向右侧寻找下一个位置为1的下标
注意初始值的设定:left = -1
*(Preferred) Two Pointer 同一种思路的另一种实现:
https://www.jiuzhang.com/solution/maximize-distance-to-closest-person/
更简明清晰:i
是外层循环,不断寻找被占用的座位(seats[i] == 1
),lastPerson
记录左侧最近的人的位置,当i
找到下一个位置seats[i] == 1
时,来计算当前的lastPerson
~ i
到这个区间内的closest person的distance。用getDist()
函数很好地封装了这个距离的计算,特殊情况,即lastPerson == -1
, i == seats.lengthy
也能被考虑到;一般情况就是(i - lastPerson) / 2
.
当然,最后在for循环外,还要检验一下右侧全0的情况,防止遗漏。
Two Pointer 另一种思路
这种思路也比较清晰:分别记录i的左右两侧的被占用的座位prev, next,选择其较小者(也就是closest person)参与全局的max distance比较。
但是还是要处理左侧全0,或者右侧全0的情况。
Keep track of prev
, the filled seat at or to the left of i
, and next
, the filled seat at or to the right of i
.
Then at seat i
, the closest person is min(i - prev, next - i)
, with one exception. i - prev
should be considered infinite if there is no person to the left of seat i
, and similarly next - i
is infinite if there is no one to the right of seat i
.
Reference
https://www.jiuzhang.com/solution/maximize-distance-to-closest-person/
https://leetcode.com/problems/maximize-distance-to-closest-person/solution/
Last updated