首页 > 试题广场 >

两数之和

[编程题]两数之和
  • 热度指数:94 时间限制:C/C++ 5秒,其他语言10秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
示例1

输入

[2, 7, 11, 15],9

输出

[0,1]
牛客相比lc太难用了,一个输入解析就恶心的不行,编辑框也太小了,写了一个python3 o(n)版本

import sys

def parse_input(input_str):
    input_arr = []
    target = 0
    s = input_str.split('],')
    s0 = s[0].replace('[', '').replace(']', '').split(',')
    for item in s0:
        input_arr.append(int(item))
    target = int(s[1])
    return input_arr, target

for line in sys.stdin:
    input_arr, target = parse_input(line)

    # 构建索引
    input_index = {}
    index = 0
    for item in input_arr:
        input_index[item] = index
        index = index + 1

    # 计算结果
    index = 0
    result = []
    for item in input_arr:
        sub_target = target - item
        if sub_target in input_index:
            print(f'[{index},{input_index[sub_target]}]')
            break
        index = index + 1


编辑于 2023-04-15 17:44:25 回复(0)