Description
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
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 one 0, and at least one 1.
Testcase
部分测试数据:
int[] nums1 = {1, 0, 0, 0, 0, 1, 0, 1};
int[] nums2 = {1, 0, 1, 0, 0, 0};
int[] nums3 = {0, 0, 0, 1, 0, 1};
int[] nums4 = {1, 0};
int[] nums5 = {0, 1};
int[] nums6 = {1, 0, 0, 1};
Solution
class Solution {
public int maxDistToClosest(int[] seats) {
int last = -1; //上一个1的位置,如果为-1说明还没遇到1
int max = Integer.MIN_VALUE;
int i = 0;
for(; i < seats.length; i++) {
//如果当前位置的数字为1
if(seats[i] == 1) {
//判断是不是之前没遇到过1,比如说[0,0,0,1,0,1],前三个数都是0
if(last == -1) {
//如果当前位置下标不为0,则将max设为当前位置下标,比如[0,0,1]:1放在最左端肯定是最大的,此时max为下标值2;如果当前位置下标为0,例如[1,0],则不能将1放在最左端,max依然待定。
max = i == 0 ? max : i;
} else {
//此时,之前已经出现过1,则应该坐在这两个人的正中间,而max根据题目要求应该取离较近的人的距离,也就是取i-seat与seat-last的较小值
int seat = (last + i)/2;
int distance = Math.min(i-seat, seat-last);
if(max < distance){
max = distance;
}
}
last = i;
}
}
//考虑[1,0,1,0,0,0]的情况,此时坐在数组的最后一位才是正解
if(seats[i-1] == 0)
max = Math.max(i-1-last, max);
return max;
}
}