LeetCode-Python-849. 到最近的人的最大距离

在一排座位( 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. 1 <= seats.length <= 20000
  2. seats 中只含有 0 和 1,至少有一个 0,且至少有一个 1

思路:

从前往后扫,得到每个元素离左边最近1 的距离,

再从后往前扫,得到每个元素离右边最近1的距离,

然后取一下交集,把最大值找出来。

class Solution(object):
    def maxDistToClosest(self, seats):
        """
        :type seats: List[int]
        :rtype: int
        """
        s = [0 for i in seats]
        
        #正着扫一遍再反着扫一遍
        for i, seat in enumerate(seats):
            if seat == 1:
                seat_index = i
                
        for index, seat in enumerate(seats):
            if seat == 1:
                s[index] = -1
                seat_index = index
            else:
                s[index] = abs(index - seat_index)
        # print s
        for i in range(len(seats) - 1, - 1, -1):
            if seats[i] == 1:
                seat_index = i
                break

        for i in range(len(seats) - 1, - 1, -1):
            if seats[i] == 1:
                seat_index = i
            else:
                # print seat_index - i
                s[i] =  min(s[i], abs(seat_index - i))

        return max(s)

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/88700307