Leetcode上的一道题

原题见:https://leetcode-cn.com/problems/two-sum/description/

题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

 题目看起来很简单,只要对列表做一个循环寻找即可。

先来看结果:

输出结果

这里实在是太简单了,只需要对输入的字符串进行切割,获取所需要的数据,然后进行寻找即可。

import re
def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    for x in nums:
        for y in nums:
            if nums.index(x) >= nums.index(y):
                continue
            else:
                if x+y == target:
                    print("下标列表为 [", nums.index(x), " , ", nums.index(y),"]")
a = input('输入一个数组:')
# b = a.strip('[]')
# 也可以这么写:
b = re.findall(r"\[(.+?)\]", a)  # 注意这里需要对[]进行转义
b = b[0].split(',')
c = []
for each in b:
    each2 = int(each)
    c.append(each2)
# print(c)
tar = int(input('输入目标值:'))
twoSum(c, tar)

但是,还得承认一点,这个代码的结果并不能通过leetcode,原因是要求定义一个类然后实例化实现。那实现起来也简单,留给读者去尝试吧。

猜你喜欢

转载自blog.csdn.net/HollyRan/article/details/85808387