849. Maximize Distance to Closest Person

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
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public int maxDistToClosest(int[] seats) {
int maxDist = 1;

int[] left = new int[seats.length]; // 左侧(不含当前座位)最接近的有人的座位的索引
int[] right = new int[seats.length]; // 右侧(不含当前座位)最接近的有人的座位的索引

int seatIndex = -1;
for (int i = 0; i < seats.length; i++) {
left[i] = seatIndex;
if (seats[i] == 1) {
seatIndex = i;
}
}
seatIndex = -1;
for (int i = seats.length - 1; i >= 0; i--) {
right[i] = seatIndex;
if (seats[i] == 1) {
seatIndex = i;
}
}

for (int i = 0; i < seats.length; i++) {
if (seats[i] == 1) {
continue;
}
if (left[i] != -1 && right[i] != -1) {
maxDist = Math.max(maxDist, Math.min(i - left[i], right[i] - i));
} else if (left[i] != -1) {
maxDist = Math.max(maxDist, i - left[i]);

} else if (right[i] != -1) {
maxDist = Math.max(maxDist, right[i] - i);
}
}

return maxDist;
}
}

References

849. Maximize Distance to Closest Person