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 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.
题目的意思就是要找到 离这个0最近的1的距离的最大值。
具体思路如下:
一个循环,如果当前值是0,就找最近的1的距离的最大值,如果是1,就跳过。
当然找0还分为几种情况:
1. 最简单的一种:两边都有1,这时候从两边的距离中选出最短的距离,和之前的最长距离比较,如果大于之前的更换,如果小于不管。
2. 如果往左边找或者右边找找不到1就到边界了,此时你肯定不能用到边界的距离当做到1的距离,因为这一边到边界的距离不存在,在这里我的处理方式是定义两个flag(按照题目的要求,只会只有最多一边找不到1),如果往右边找不到,那么让它到右边的距离等于左边找到1的距离,左边同理可得。
int maxDistToClosest(vector<int>& seats) {
int length = seats.size();
int closest = 0;
for(int i = 0 ; i < length ; i++)
{
if(seats[i] == 1)
continue;
int left_min=0,right_min=0;
int flag_left = 0,flag_right = 0;
//左边开始找
for(int m = i - 1 ; m >= 0 ; m --)
{
left_min++;
if(seats[m] == 1)
{
//左边找到了
flag_left = 1;
break;
}
}
//右边开始找
for(int n = i+1;n<=seats.size()-1;n++)
{
right_min++;
if(seats[n] == 1)
{
//右边找到了
flag_right = 1;
break;
}
}
if (flag_left == 0)
{
left_min = right_min;
}
if(flag_right == 0)
{
right_min = left_min;
}
closest = max(closest,min(left_min,right_min));
}
return closest;
}