1. 程式人生 > 實用技巧 >849. Maximize Distance to Closest Person

849. Maximize Distance to Closest Person

In a row ofseats,1represents a person sitting in that seat, and0represents 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.

給一個數組,要麼0要麼1,至少會有1個0和1個1,1表示有人坐了,0表示沒有人坐。

求找到一個位置,是的離最近的人的距離最大。

問題就是轉換成找距離最遠的兩個1端點,然後答案是兩個1的距離除以2,當然邊界條件是隻有1個1,這個時候就不需要除以2

class Solution(object):
    def maxDistToClosest(self, seats):
        """
        :type seats: List[int]
        :rtype: int
        """
        index = 0
        while index < len(seats) and
seats[index] != 1: index += 1 ans = index last = index for i in range(index + 1, len(seats), 1): if seats[i] == 1: ans = max(ans, (i - last) // 2) last = i ans = max(ans, (len(seats) - last - 1)) return ans