Kattis平台Integer Lists挑战代码测试通过但提交报错求助
问题分析与修正方案
问题1:频繁反转列表导致超时
你的代码每次遇到R就调用list.reverse(),该操作时间复杂度为O(n)。当测试用例存在大量R操作时,会直接触发超时。正确做法是用布尔变量记录反转状态,无需每次实际反转列表。
问题2:输出格式不匹配
Python默认打印列表时元素间带空格(如[2, 1]),但题目要求输出无空格格式(如[2,1]),格式不匹配会被判题系统拒绝。
问题3:空列表处理逻辑错误
当elements <= 0时你直接输出error,但实际只有存在D操作时才是错误。若无D操作,即使列表为空,应输出[]而非error。
修正后的代码
import sys def main(): input = sys.stdin.read().splitlines() idx = 0 t = int(input[idx]) idx += 1 for _ in range(t): ops = input[idx] idx +=1 n = int(input[idx]) idx +=1 lst_str = input[idx].strip('[]') idx +=1 lst = list(map(int, lst_str.split(','))) if lst_str else [] reverse_flag = False error = False for op in ops: if op == 'R': reverse_flag = not reverse_flag elif op == 'D': if not lst: error = True break if reverse_flag: lst.pop() else: lst.pop(0) if error: print("error") else: if reverse_flag: lst.reverse() # 构造符合要求的输出格式 print(f"[{','.join(map(str, lst))}]") if __name__ == "__main__": main()
修正说明
- 用标志位替代实际反转:新增
reverse_flag变量,遇到R仅翻转标志位,最后根据标志位决定是否反转列表,将多次O(n)操作降为最多一次O(n)操作,大幅提升效率。 - 手动构造输出格式:通过
','.join(map(str, lst))生成无空格的元素字符串,再包裹方括号,确保输出格式完全匹配题目要求。 - 修正空列表处理逻辑:仅当执行
D操作且列表为空时标记错误,否则根据反转状态输出正确结果或空列表。
内容的提问来源于stack exchange,提问作者Rehan
相关产品推荐
相关产品推荐

