[英]How to find the index of the furthest item in a list
Leetcode 有一個問題來計算列表中已占座位和空座位之間的最大距離。 我在嘗試獲取離座位最遠的座位的索引時遇到了麻煩。 當前代碼計算最大距離,而不是最遠座位的索引。 [1,0,0,0,1,0,1] 將是一個示例列表。 1 是一個座位,0 是空的。
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)
這是獲得 1(或 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
最遠座位的index
由index
變量給出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.