1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int maxDistToClosest(int[] seats) {
int lastSeated = -1, ans = 0;
for (int i = 0; i < seats.length; i++) {
if (seats[i] == 1) {
ans = lastSeated < 0 ? i : Math.max(ans, (i - lastSeated) / 2);
lastSeated = i;
}
}
ans = Math.max(ans, (seats.length - 1 - lastSeated));
return ans;
}
}

是exam room的低阶版. 记录上一个seated的位置即可. 需要注意edge case, 也就是当第0个位置没人坐或者在某个位置后直到数组结束都是空位. 这两种情况对应第6行和第10行的操作.

时间复杂度: O(n)
空间复杂度: O(1)