849. Maximize Distance to Closest Person*
https://leetcode.com/problems/maximize-distance-to-closest-person/
题目描述
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 <= 20000seats contains only 0s or 1s, at least one 0, and at least one 1.
C++ 实现 1
要找到最大的距离, 实际是要比较三个距离, 起始距离, 中间距离以及末尾距离, 这几个距离定义如下:
- 起始距离:
[0, 0, 0, 1], 到seats中第一个1的距离, 大小为 3. - 中间距离:
[0, 1, 0, 0, 1, 0],seats中中间两个1之间的距离, 大小为 3. - 末尾距离:
[1, 0, 0, 0],seats从后向前, 遇到第一个1的距离, 大小为 3.
分别用 start_dis, mid_dis 以及 end_dis 来统计, 最后比较 start_dis 与 mid_dis / 2 以及 end_dis 的大小, 取其中的最大值即可.
使用 has_start_dis 判断是否遇到了第一个 1, 由此来更新起始距离 start_dis.
使用 j 来更新最后一个 1 的距离, 一方面可以不断更新中间距离 mid_dis, 另一方面最后可以求得末尾距离 end_dis.
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int start_dis = 0, mid_dis = 0, end_dis = 0;
bool has_start_dis = false;
int j = -1;
for (int i = 0; i < seats.size(); ++ i) {
if (seats[i] == 1) {
if (!has_start_dis) { // 判断是否初次遇到 1
has_start_dis = true;
} else {
mid_dis = std::max(mid_dis, i - j);
}
j = i;
}
if (!has_start_dis && seats[i] == 0) start_dis ++;
}
end_dis = seats.size() - 1 - j;
if (start_dis >= mid_dis / 2 && start_dis >= end_dis)
return start_dis;
else if (end_dis > mid_dis / 2 && end_dis > start_dis)
return end_dis;
else
return mid_dis / 2;
}
};
本文探讨了在一系列座位中,如何通过算法找到离最近的人最大距离的座位。通过分析起始、中间和末尾距离,该算法能够帮助如Alex这样的个体找到最佳位置,以保持社交距离。

159

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



