题目描述:
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. 1 <= seats.length <= 20000
2. seats contains only 0s or 1s, at least one 0, and at least one 1.
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int result=0;
int pre=-1; //上一个有人的座位的下标
for(int i=0;i<seats.size();i++)
{
if(seats[i]==1)
{
if(pre==-1) result=i; //第一次遇到一个有人的座位
else result=max(result,(i-pre)/2);
pre=i;
}
else if(i==seats.size()-1) // 最后一个座位没人时也可以更新
result=max(result,(int)seats.size()-1-pre);
}
return result;
}
};
本文介绍了一种算法,用于计算在一系列座位中,一个人如何坐才能最大化与最近的人之间的距离。通过遍历座位数组,算法记录了上一个有人的座位位置,并计算当前空位与上一个有人座位的距离,从而找到最大距离。
720

被折叠的 条评论
为什么被折叠?



