在一排座位( seats)中,1 代表有人坐在座位上,0 代表座位上是空的。
至少有一个空座位,且至少有一人坐在座位上。
亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。
返回他到离他最近的人的最大距离。
示例 1:
输入:[1,0,0,0,1,0,1]
输出:2
解释:
如果亚历克斯坐在第二个空位(seats[2])上,他到离他最近的人的距离为 2 。
如果亚历克斯坐在其它任何一个空位上,他到离他最近的人的距离为 1 。
因此,他到离他最近的人的最大距离是 2 。
示例 2:
输入:[1,0,0,0]
输出:3
解释:
如果亚历克斯坐在最后一个座位上,他离最近的人有 3 个座位远。
这是可能的最大距离,所以答案是 3 。
提示:
1 <= seats.length <= 20000
seats 中只含有 0 和 1,至少有一个 0,且至少有一个 1。
思
路
分
析
:
\color{blue}思路分析:
思路分析:这道题我们只要找到最大的空位置连续段即可,然后将连续空位置长度除2(人坐在这段连续空位置段中间),这样就可以找到一个结果。
蛋式有两种特殊情况,就是分别在首端、尾端的连续空位置段,比如[1,0,0,0]这时尾端出现空位置段,坐在seats[3]才是最终结果。
因此首端出现连续空位置段,坐在第一个位置才是最好的选择,尾端出现连续空位置段,坐在最后一个位置才是最好的选择。
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int maxRes = 0, index = 0;
int beforeIndex = 0, seatsSize = seats.size();//beforeIndex记录空位置段的前一个坐了人的下标
//如果首端出现了连续的空位置段
while (seats[index] == 0){
++index;
}
maxRes = index;//坐在第一个位置
while (index < seatsSize){
//跳过坐了人的位置
while (index < seatsSize && seats[index] == 1){
++index;
}
//确定连续空位置区间
beforeIndex = index - 1;
while (index < seatsSize && seats[index] == 0){
++index;
}
//更新最大结果
if (index == seatsSize){
//连续的空位置出现尾端,坐在尾端
maxRes = max(maxRes, index - beforeIndex - 1);
}
else{
//坐在空位置段的中间
maxRes = max(maxRes, (index - beforeIndex) / 2);
}
}
return maxRes;
}
};
也可以直接计算空位置的长度。注意如果空位置长度为奇数比如[1, 0, 0, 0,1]结果是(3 + 1)/ 2 ,因为距离是间隔,而空位置的长度是座位个数。
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int maxRes = 0, index = 0;
int seatsSize = seats.size();
//如果首端出现了连续的空位置段
while (seats[index] == 0){
++index;
}
maxRes = index;//坐在第一个位置
while (index < seatsSize){
//跳过坐了人的位置
while (index < seatsSize && seats[index] == 1){
++index;
}
int emptySeatCount = 0;//连续空位置段长度
while (index < seatsSize && seats[index] == 0){
++index;
++emptySeatCount;
}
//更新最大结果
if (index == seatsSize){
//连续的空位置出现尾端,坐在尾端
maxRes = max(maxRes, emptySeatCount);
}
else{
//坐在空位置段的中间
maxRes = max(maxRes, (emptySeatCount + 1) / 2);
}
}
return maxRes;
}
};