849. 到最近的人的最大距离
为保证权益,题目请参考 849. 到最近的人的最大距离(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int maxDistToClosest(vector<int> &seats)
{
int ans = -1;
// front
int frontOneIdx = -1;
for (int i = 0; i < seats.size(); i++)
{
if (seats[i] == 1)
{
frontOneIdx = i;
ans = max(ans, frontOneIdx);
break;
}
}
// back
int backOneIdx = -1;
for (int i = seats.size() - 1; i >= 0; i--)
{
if (seats[i] == 1)
{
backOneIdx = i;
ans = max(ans, int(seats.size()) - 1 - backOneIdx);
break;
}
}
int continueZeroCount = 0;
for (int i = frontOneIdx; i <= backOneIdx; i++)
{
if (seats[i] == 0)
{
continueZeroCount += 1;
}
else
{
ans = max(ans, (continueZeroCount + 1 ) / 2);
continueZeroCount = 0;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53