You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
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 the closest person.
Example 1:
Input: seats = [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (i.e. 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: seats = [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
Example 3:
Input: seats = [0,1]
Output: 1
题目解析:坐下每个点距离最近的人的距离,这要求我们要知道左右两边人的距离,也就是min(left, right),我们可以选择先计算出所有点距左右两边的人的距离,再进行判断,或者每到一个点计算左右两边距离取最小值。
- 提前计算所有点距左右两边的距离
public int maxDistToClosest(int[] seats) {
int length = seats.length;
int[] left = new int[length];
int[] right = new int[length];
Arrays.fill(left, length);
Arrays.fill(right, length);
//获取到每个可坐下的点距左边边的人的距离
for (int i = 0; i < length; i++) {
if (seats[i] == 1) left[i] = 0;
else if (i > 0) left[i] = left[i - 1] + 1;
}
//获取到每个可坐下的点距右边的人的距离
for (int i = length - 1; i >= 0; i--) {
if (seats[i] == 1) right[i] = 0;
else if (i < length - 1) right[i] = right[i + 1] + 1;
}
int maxDis = 0;
//获取每个点据人的最小值中的最大值
for (int i = 0; i < length; i++) {
if (seats[i] == 0)
maxDis = Math.max(maxDis, Math.min(left[i], right[i]));
}
return maxDis;
}
- 每到一个点进行计算
public int maxDistToClosest(int[] seats) {
int N = seats.length;
int prev = -1, future = 0;
int ans = 0;
for (int i = 0; i < N; ++i) {
if (seats[i] == 1) {
prev = i;
} else {
while (future < N && seats[future] == 0 || future < i)
future++;
int left = prev == -1 ? N : i - prev;
int right = future == N ? N : future - i;
ans = Math.max(ans, Math.min(left, right));
}
}
return ans;
}