首页 > 其他 > 详细

849. 到最近的人的最大距离

时间:2020-04-29 10:29:58      阅读:56      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 技术分享图片

 

 

思路:

1、找到seats中第一、最后一个1的位置,分别为:low、high;
2、求得最后一个1的后面1的个数recindex(因为要坐最后那么所隔距离就为recindex);
3、遍历seats从low到high的元素,用res[]存放每一段连续的0的个数;
4、求得res中的最大值leng,通过leng的奇偶求得最远距离ans;
5、返回max(low,recindex,ans)
注:要是seats中只有一个1,那么返回max(low,recindex),即首尾哪边离得远坐哪边。
 1 class Solution(object):
 2     def maxDistToClosest(self, seats):
 3         """
 4         :type seats: List[int]
 5         :rtype: int
 6         """
 7         # 记录最后一个1之后0的个数
 8         recindex = seats[::-1].index(1)
 9         # 分别找到第一个1和最后一个1的下标
10         low = seats.index(1)
11         high = len(seats) - 1 - recindex
12         # seats中只有一个1,那就是首尾哪边离得远坐哪边
13         if low == high:
14             return max(low, recindex)
15         # 存放seats中连续的0的个数
16         res = []
17         num = 0
18         for i in range(low + 1, high + 1):
19             if seats[i] == 0:
20                 num += 1
21             else:
22                 res.append(num)
23                 num = 0
24         # 取得最长连续0的个数,判断奇偶,因为坐就要坐中间
25         leng = max(res)
26         if leng % 2 == 1:
27             ans = leng // 2 + 1
28         else:
29             ans = leng // 2
30         # 返回是首、尾、及中间位置的最远距离
31         return max(ans, low, recindex)
32 
33 
34 if __name__ == __main__:
35     solution = Solution()
36     print(solution.maxDistToClosest([1, 0, 0, 0]))

 

 

849. 到最近的人的最大距离

原文:https://www.cnblogs.com/panweiwei/p/12800183.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!