Source From Here
Question
In a row of seats, 1 represents a person sitting in that seat, and 0 represents 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.
Example 1:
Example 2:
Solution
Naive
Discussion - Solution in Python 3 (link)
Question
In a row of seats, 1 represents a person sitting in that seat, and 0 represents 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.
Example 1:
Example 2:
Solution
Naive
- class Solution:
- def maxDistToClosest(self, seats):
- max_dist = 0
- def dist2cp(zero_seq, is_edged):
- if is_edged:
- return zero_seq
- else:
- return (zero_seq-1) // 2 + 1
- zc = 0
- is_edge = True
- for v in seats:
- if v == 1:
- dist = dist2cp(zc, is_edge)
- if dist > max_dist:
- max_dist = dist
- zc = 0
- is_edge = False
- else:
- zc += 1
- if zc > 0:
- dist = dist2cp(zc, True)
- if dist > max_dist:
- max_dist = dist
- return max_dist
- if __name__ == '__main__':
- s = Solution()
- for seats, ans in [
- ([1, 0, 0, 0, 1, 0, 1], 2),
- ([0, 0, 0, 1, 0, 0, 0, 1], 3),
- ([1, 0, 0, 1, 1], 1)
- ]:
- rel = s.maxDistToClosest(seats)
- print("{}: {}".format(seats, rel))
- assert ans == rel
Discussion - Solution in Python 3 (link)
- class Solution:
- def maxDistToClosest(self, seats: List[int]) -> int:
- L = len(seats)
- # 1) Get seat of each person
- # e.g seats = [1, 0, 0, 0, 1, 0, 1]
- # S = [0, 4, 6]
- S = [i for i in range(L) if seats[i]]
- # 2) Calculate distance between two sequential person
- # S = [0, 4, 6]
- # d = [(4-0//2)=2, (6-4)//2=1] = [2, 1]
- d = [S[i+1]-S[i] for i in range(len(S)-1)] if len(S) > 1 else [0]
- # 3) Find maximum distance
- return max(max(d)//2, S[0], L-1-S[-1])
沒有留言:
張貼留言