Leetcode has a question to calculate the max distance between taken and empty seats in a list. I'm having trouble trying to get the index of the seat that is furthest away from a seat taken. The current code calculates the max distance, just not the index of the seat that is furthest away. [1,0,0,0,1,0,1] would be an example list. 1 is a seat taken and 0 is empty.
person_idx = None
last_idx = len(seats) - 1
dist = 0
# scan for each seats
for cur_idx, seat in enumerate(seats):
# this seat is taken by someone
if seat == 1:
if person_idx is None:
# No person on the left, Alex seat on left hand side
dist = max(dist, cur_idx)
else:
# Surrounded by two person, Alex seat on the middle
dist = max(dist, (cur_idx - person_idx) // 2)
person_idx = cur_idx
print(person_idx)
# No person on the right, Alex seat on the right hand side
dist = max(dist, last_idx - person_idx)
print(dist)
Here is the way to get the furthest index of 1 (or 0):
seat = [1, 0, 0, 0, 1, 0, 1]
rev = list(reversed(seat))
index = len(seat) - rev.index(1) - 1
# rev.index() can be used with 1 or 0, depending on what you are looking for
The index of the furthest seat is given by the index
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.