在一排座位( 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
。
C
int maxDistToClosest(int* seats, int seatsSize)
{
int n=seatsSize;
int* temp=(int*)malloc(sizeof(int)*((n+1)/2));
int k=0;
int count=1;
for(int i=1;i<n;i++)
{
if(seats[i]==0)
{
if(seats[i-1]==0)
{
count++;
}
else
{
count=1;
}
}
else
{
if(seats[i-1]==0)
{
temp[k++]=count;
}
count=0;
}
}
if(count)
{
temp[k]=count;
}
int m=k+1;
for(int i=1;i<m-1;i++)
{
temp[i]=(temp[i]+1)/2;
}
if(seats[0]==1 && m>1)
{
temp[0]=(temp[0]+1)/2;
}
if(seats[n-1]==1 && m>1)
{
temp[m-1]=(temp[m-1]+1)/2;
}
if(seats[0]==1 && seats[n-1]==1 && m==1)
{
temp[0]=(temp[0]+1)/2;
}
int res=temp[0];
for(int i=0;i<m;i++)
{
if(temp[i]>res)
{
res=temp[i];
}
}
return res;
}
C++
class Solution {
public:
int maxDistToClosest(vector<int>& seats)
{
int n=seats.size();
int res=0;
vector<int> temp;
int count=1;
for(int i=1;i<n;i++)
{
if(seats[i]==0)
{
if(seats[i-1]==0)
{
count++;
}
else
{
count=1;
}
}
else
{
if(seats[i-1]==0)
{
temp.push_back(count);
}
else
{
count=0;
}
}
}
if(count)
{
temp.push_back(count);
}
int m=temp.size();
for(int i=1;i<m-1;i++)
{
temp[i]=(temp[i]+1)/2;
}
if(seats[0]==1 && m>1)
{
temp[0]=(temp[0]+1)/2;
}
if(seats[n-1]==1 && m>1)
{
temp[m-1]=(temp[m-1]+1)/2;
}
if(seats[0]==1 && seats[n-1]==1 && m==1)
{
temp[0]=(temp[0]+1)/2;
}
res=*max_element(temp.begin(),temp.end());
return res;
}
};
python
class Solution:
def maxDistToClosest(self, seats):
"""
:type seats: List[int]
:rtype: int
"""
n=len(seats)
temp=[]
count=1
for i in range(1,n):
if seats[i]==0:
if seats[i-1]==0:
count += 1
else:
count = 1
else:
if seats[i-1]==0:
temp.append(count)
else:
count=0
if count:
temp.append(count)
m=len(temp)
for i in range(1,m-1):
temp[i]=(temp[i]+1)//2
if seats[0]==1 and m>1:
temp[0]=(temp[0]+1)//2
if seats[n-1]==1 and m>1:
temp[m-1]=(temp[m-1]+1)//2
if seats[0]==1 and seats[n-1]==1 and m==1:
temp[0]=(temp[0]+1)//2
return max(temp)