|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +# In a row of seats, 1 represents a person sitting in that seat, |
| 5 | +# and 0 represents that the seat is empty. |
| 6 | +# |
| 7 | +# There is at least one empty seat, and at least one person sitting. |
| 8 | +# |
| 9 | +# Alex wants to sit in the seat such that the distance between him |
| 10 | +# and the closest person to him is maximized. |
| 11 | +# |
| 12 | +# Return that maximum distance to closest person. |
| 13 | +# |
| 14 | +# Example 1: |
| 15 | +# |
| 16 | +# Input: [1,0,0,0,1,0,1] |
| 17 | +# Output: 2 |
| 18 | +# Explanation: |
| 19 | +# If Alex sits in the second open seat (seats[2]), |
| 20 | +# then the closest person has distance 2. |
| 21 | +# If Alex sits in any other open seat, the closest person has distance 1. |
| 22 | +# Thus, the maximum distance to the closest person is 2. |
| 23 | +# Example 2: |
| 24 | +# |
| 25 | +# Input: [1,0,0,0] |
| 26 | +# Output: 3 |
| 27 | +# Explanation: |
| 28 | +# If Alex sits in the last seat, the closest person is 3 seats away. |
| 29 | +# This is the maximum distance possible, so the answer is 3. |
| 30 | +# Note: |
| 31 | +# - 1 <= seats.length <= 20000 |
| 32 | +# - seats contains only 0s or 1s, at least one 0, and at least one 1. |
| 33 | + |
| 34 | +try: |
| 35 | + xrange # Python 2 |
| 36 | +except NameError: |
| 37 | + xrange = range # Python 3 |
| 38 | + |
| 39 | + |
| 40 | +class Solution(object): |
| 41 | + def maxDistToClosest(self, seats): |
| 42 | + """ |
| 43 | + :type seats: List[int] |
| 44 | + :rtype: int |
| 45 | + """ |
| 46 | + prev, result = -1, 1 |
| 47 | + for i in xrange(len(seats)): |
| 48 | + if seats[i]: |
| 49 | + if prev < 0: |
| 50 | + result = i |
| 51 | + else: |
| 52 | + result = max(result, (i-prev)//2) |
| 53 | + prev = i |
| 54 | + return max(result, len(seats)-1-prev) |
0 commit comments