如何查找列表中距离指定值最远的元素索引(含LeetCode最大座位距离场景)
解决方案
修改思路
原有代码仅计算了最大距离数值,未同步记录对应空座位的索引,我们只需要新增一个变量存储目标索引,在每次更新最大距离时,同步计算当前场景下的最优空座位索引并更新即可。
需要覆盖三种场景的索引计算逻辑:
- 前缀连续空座位(左侧无已占座位):最优空座位索引为
0,距离为第一个已占座位的索引值 - 两个已占座位中间的空座位:最优空座位索引为两个已占座位索引的中点,即
person_idx + (cur_idx - person_idx) // 2 - 后缀连续空座位(右侧无已占座位):最优空座位索引为列表最后一个索引,距离为
最后一个索引 - 最后一个已占座位的索引
修改后代码
seats = [1,0,0,0,1,0,1] person_idx = None last_idx = len(seats) - 1 max_dist = 0 target_idx = 0 # 新增变量存储目标空座位索引 for cur_idx, seat in enumerate(seats): if seat == 1: if person_idx is None: # 前缀空座位场景 current_dist = cur_idx if current_dist > max_dist: max_dist = current_dist target_idx = 0 else: # 中间空座位场景 current_dist = (cur_idx - person_idx) // 2 if current_dist > max_dist: max_dist = current_dist target_idx = person_idx + current_dist person_idx = cur_idx # 后缀空座位场景 current_dist = last_idx - person_idx if current_dist > max_dist: max_dist = current_dist target_idx = last_idx print("最大距离:", max_dist) print("最远空座位索引:", target_idx)
测试验证
输入示例[1,0,0,0,1,0,1]运行后,输出的最远空座位索引为2,符合预期:该位置距离左右两个已占座位的距离都是2,为所有空座位中的最大值。
内容的提问来源于stack exchange,提问作者cjaka301
相关产品推荐
相关产品推荐

