You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3使用sys模块读取输入求两个有序整数列表的交集

完整实现代码
import sys

def intersection(lst1, lst2):
    # 原有逻辑保留,小数据量下可用
    lst3 = [value for value in lst1 if value in lst2]
    return lst3

if __name__ == "__main__":
    # 读取所有输入行,过滤空行
    input_lines = [line.strip() for line in sys.stdin.readlines() if line.strip()]
    # 转换第一行为第一个整数列表
    lst1 = list(map(int, input_lines[0].split()))
    # 转换第二行为第二个整数列表
    lst2 = list(map(int, input_lines[1].split()))
    # 计算交集
    res = intersection(lst1, lst2)
    # 按通用判题要求输出空格分隔结果,如需输出列表格式直接改为print(res)即可
    print(' '.join(map(str, res)))
注意事项
  • 若测试用例中列表元素以逗号分隔,将.split()改为.split(',')即可适配
  • 原有交集函数的时间复杂度为O(n*m),如果输入列表规模较大,可替换为适配有序列表的双指针实现,时间复杂度可优化为O(n+m):
def intersection(lst1, lst2):
    i = j = 0
    res = []
    while i < len(lst1) and j < len(lst2):
        if lst1[i] == lst2[j]:
            res.append(lst1[i])
            i += 1
            j += 1
        elif lst1[i] < lst2[j]:
            i += 1
        else:
            j += 1
    return res

内容的提问来源于stack exchange,提问作者Mining

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:36:02