1,题目要求
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.
对于一系列的座位,1表示有人,0表示没人,找到一个座位,使得距离该座位的最近的人的距离最大化。
2,题目思路
对于这道题,如果是在两个座位之间,则最近距离的最大值就是正中间的位置,也就是d/2。在依次遍历座位,对d进行累加,如果没有再遍历到1(即有人的位置),则最后取res和d的最大值。
3,程序源码
class Solution {
public:
int maxDistToClosest(vector<int> &seats) {
int res = -1, d = 0;
for (auto x : seats) {
if(x == 1)
{
if(res == -1) //说明是开始的位置
res = max(res, d);
else
res = max(res, d/2); //说明后面的1,则是取中间位置
d = 1;
}
else
d++;
}
return max(res, d-1);
}
};