繁体   English   中英

如何找到列表中最远项的索引

[英]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

最远座位的indexindex变量给出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM